Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

This type of sorting is called "Selection Sort" because it works by repeatedly selecting

an element. It works as follows: first find the smallest element in the array and
exchange it with the element in the first position, then find the second smallest
element and exchange it with the element in the second position, and continue in this
way until the entire array is sorted.
Pseudocode:
SelectionSort(array)
BEGIN
for i = 1 to n-1
min_subsrcipt = i
min _value = array[i]
for j = i + 1 to n - 1
if (array[j] < min_value)
min_subscript = j
min_value = array[j]
endif
endfor
array[min_subscript] = array[i]
array[i] = min_value
Within the selection structure mentioned in 2(d), a swap will take place. The following
steps explains how the swap will take place:
i. Create a temporary variable to store the value that is in position phase -1.
temp = arr[phase 1]
ii. Store the value that is in position min into position phase -1.
arr[phase-1] = arr[min]
iii. Store the value in temp into position min.
arr[min] = temp
3. No further instructions are need when the for loop in 1 above is exited.

endfor

END

Implementation
void
selectionSort(int numbers[], int array_size) { int i, j; int min, temp; for (i = 0; i <
array_size-1; i++) { min = i; for (j = i+1; j < array_size; j++) { if (numbers[j] <
numbers[min]) min = j; } temp = numbers[i]; numbers[i] = numbers[min];
numbers[min] = temp; } }

You might also like