Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sorting Arrays ANSI-C. Selection Sort Assume want to sort a table of integers, of size length, in increasing order. Sketch of algorithm: –Find position.

Similar presentations


Presentation on theme: "Sorting Arrays ANSI-C. Selection Sort Assume want to sort a table of integers, of size length, in increasing order. Sketch of algorithm: –Find position."— Presentation transcript:

1 Sorting Arrays ANSI-C

2 Selection Sort Assume want to sort a table of integers, of size length, in increasing order. Sketch of algorithm: –Find position of smallest in table[0..length-1], place it in place 0 –Find position of smallest in table [1..length-1], place it in place 1 –Find position of smallest in table [2..length-1],, place it in place 2 –…. –Find position of smallest in table [length-2..length-1], place it in place length-2 –Find position of smallest in table [length-1..length-1], place it in place length –1 General form: –Find position of smallest in table[i..length-1] and place it in place i –For i:0..length-2 It calls for a loop

3 int i = 0; while (i < ?){ find position of smallest in table[i..length-1] place element at that position in place i i = i + 1; } So, we need to write two functions: int smallestPos ( int table[], int first, int last); And a function that interchanges the elements in the array in places i, that the position where the smallest in table[i..length-1] void interchange( int table[], int i, int k);

4 void selectionSort( int table[], int length){ int i = 0; int smallest; while (i < length - 1){ smallest = smallestPos(table, i, length-1); interchange( table, i, smallest); i = i + 1; } }

5 int smallestPos ( int table[], int first, int last){ int pos = first; int i = first + 1; while ( i <= last) { if (table[pos] > table[i]) pos = i; i = i + 1; } return pos; }

6 void interchange( int table[], int i, int k){ int temp = table[i]; table[i] = table[k]; table[k] = temp; }


Download ppt "Sorting Arrays ANSI-C. Selection Sort Assume want to sort a table of integers, of size length, in increasing order. Sketch of algorithm: –Find position."

Similar presentations


Ads by Google