Straight Selection Sort Algorithm

Divides the array into two parts: already sorted, and not yet sorted.

On each pass, finds the smallest of the unsorted elements, 7and swaps it into its correct place, thereby increasing the number of sorted elements by one.




Running Time

The number of comparisons when the array contains N elements is Sum = (N-1) + (N-2) + . . . + 2 + 1

Sum = (N-1) + (N-2) + . . . + 2 + 1
+ Sum = 1 + 2 + . . . + (N-2) + (N-1)

which equals

2* Sum = N + N + . . . + N + N


which equals
2 * Sum = N * (N-1)

which equals
Sum = N * (N-1)/ 2

thus
Sum = O(N^2)


template 
int  MinIndex(ItemType values [ ], int  start, int end)
//  Post: Function value = index of the smallest value
//  in values [start]  . . values [end].
{
	int  indexOfMin = start ;

	for(int index = start + 1 ; index <= end ; index++)	
	  if  (values[ index] < values [indexOfMin])
		 indexOfMin = index ;

	return   indexOfMin;
           
}


template 
void  SelectionSort (ItemType values[ ], 
  int  numValues )	
	
// Post: Sorts array values[0 . . numValues-1 ]
// into ascending order by key
{
	int  endIndex = numValues - 1 ;

	for (int current = 0 ; current < endIndex;
    current++)	

    Swap (values[current], 
      values[MinIndex(values,current, endIndex)]);
           
} 	


 

 

© Lynne Grewe