Yesterday at work, I decided to figure out how to sort numbers without using the library method Array.Sort . I worked and worked when time was allowed, and finally, at the end of today I was able to find the basic algorithm of work. This might be pretty dumb and slower, but I'm glad that I have working code.
But there is something wrong or missing in the logic, which causes the output to hang before printing a line: Numbers Sorted. (12/17/2011 2:11:42 AM) Numbers Sorted. (12/17/2011 2:11:42 AM)
This delay is directly proportional to the number of elements in the array. To be specific, the output simply hangs in the position where I put the tilde in the results section below. Content after the tilde is printed after this noticeable delay.
Here is the code that does the sorting:
while(pass != unsortedNumLen) { for(int i=0,j=1; i < unsortedNumLen-1 && j < unsortedNumLen; i++,j++) { if (unsorted[i] > unsorted[j]) { pass = 0; swaps++; Console.Write("Swapping {0} and {1}:\t", unsorted[i], unsorted[j]); tmp = unsorted[i]; unsorted[i] = unsorted[j]; unsorted[j] = tmp; printArray(unsorted); } else pass++; } }
Results:
Numbers unsorted. (12/17/2011 2:11:19 AM) 4 3 2 1 Swapping 4 and 3: 3 4 2 1 Swapping 4 and 2: 3 2 4 1 Swapping 4 and 1: 3 2 1 4 Swapping 3 and 2: 2 3 1 4 Swapping 3 and 1: 2 1 3 4 Swapping 2 and 1: 1 2 3 4 ~ Numbers sorted. (12/17/2011 2:11:42 AM) 1 2 3 4 Number of swaps: 6
Can you help identify the problem with my attempt?
Link to the full code
This is not homework, I just work.
source share