Sorting Arrays ANSIC Selection Sort Assume want to

  • Slides: 6
Download presentation
Sorting Arrays ANSI-C

Sorting Arrays ANSI-C

Selection Sort • Assume want to sort a table of integers, of size length,

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

int i = 0; while (i < ? ){ find position of smallest in

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 smallest. Pos ( 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);

void selection. Sort( int table[], int length){ int i = 0; int smallest; while

void selection. Sort( int table[], int length){ int i = 0; int smallest; while (i < length - 1){ smallest = smallest. Pos(table, i, length-1); interchange( table, i, smallest); i = i + 1; } }

int smallest. Pos ( int table[], int first, int last){ int pos = first;

int smallest. Pos ( 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; }

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

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