0% found this document useful (0 votes)
22 views

Temp Arr (Phase - 1) Arr (Phase-1) Arr (Min) Arr (Min) Temp

Selection sort works by repeatedly finding the minimum element in an array and exchanging it with the element in the first position. It does this by first finding the smallest element and swapping it into the first position, then finding the second smallest and swapping it into the second position, continuing until the array is fully sorted. The algorithm uses a nested loop - an outer loop iterates through the array, and an inner loop finds the minimum remaining element and swaps it into the current position.

Uploaded by

TaraHenry
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Temp Arr (Phase - 1) Arr (Phase-1) Arr (Min) Arr (Min) Temp

Selection sort works by repeatedly finding the minimum element in an array and exchanging it with the element in the first position. It does this by first finding the smallest element and swapping it into the first position, then finding the second smallest and swapping it into the second position, continuing until the array is fully sorted. The algorithm uses a nested loop - an outer loop iterates through the array, and an inner loop finds the minimum remaining element and swaps it into the current position.

Uploaded by

TaraHenry
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 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