Dsa Selection Sort
Dsa Selection Sort
Sorting Algorithms
1 Definition
3 ADT Specification
5 ADT Implementation
1 Definition
Selection Sort
It is a simple sorting algorithm. This is an in-place comparison-
based algorithm in which the list is divided into two parts, the sorted part
at the left end and the unsorted part at the right end. Initially, the sorted
part is empty and the unsorted part is the entire list.
Example:
INPUT: UNSORTED ARRAY OUTPUT: SORTED ARRAY
Arr [5] = {20, 12, 10, 15, 2} Arr [5] = {2, 5, 6, 7, 11}
0 1 2 3 4 0 1 2 3 4
20 12 10 15 2 2 10 12 15 20
4 Steps
ALGORITHMS:
OPERATION:
Selection Sort - a user-defined function to sort the random
ordered elements of array in ascending or descendingorder.
4 ADT Representation
PSEUDOCODE: arr : array of items n : size of list
for i = 1 to n - 1
min = i /* set current element as minimum*/
end procedure
5 ADT Implementation
The following implements the selection sort through a user-defined
function.
void selectionSort(int arr[], int Mxsize)
{
for (int i = 0; i < Mxsize-1; i++) { if (min != i) {
int min = i; //sets min to index i [0] int temp = arr[min];
//iterate the elements arr[min] = arr[i];
for (int j = i + 1; j < Mxsize; j++) arr[i] = temp;
{ }
if (arr[j] < arr[min]) { //compare elements to minimum }
min = j; //sets the smallest number j in array to min. }
}
}
5 ADT Implementation
if (min != i) {
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}
cout << "****A program that will arrange the numbers in ascending order using
SELECTION SORT.****\n\n";
cout << "Enter how many numbers will be sorted: ";
cin >> Mxsize;
cout << "\nEnter " <<Mxsize <<" numbers in random order: " << endl;
// function call
selectionSort(myarr,Mxsize);
//display unsorted array
cout << "UNSORTED ARRAY: " << endl; //display sorted array in ascending order
for (int i = 0; i < Mxsize; i++) { cout << "SORTED ARRAY: " << endl;
cout << myarr[i] << "\t"; for (int i = 0; i < Mxsize; i++) {
} cout << myarr[i] << "\t";
}
5 ADT Implementation
When the program was executed, it prints the output in ASCENDING:
5 ADT Implementation
When the program was executed, it prints the output in DESCENDING:
Thanks!