PROGRAM ON SELECTION SORT IN ARRAY C++

#include<iostream>

using namespace std;

void selectionSort(int a[], int n) {

   int i, j, min, temp;

   for (i = 0; i < n - 1; i++) {

      min = i;

      for (j = i + 1; j < n; j++)

      if (a[j] < a[min])

      min = j;

      temp = a[i];

      a[i] = a[min];

      a[min] = temp;

   }

}

int main() {

   int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 };

   int n = sizeof(a)/ sizeof(a[0]);

   int i;

   cout<<"Given array is:"<<endl;

   for (i = 0; i < n; i++)

   cout<< a[i] <<" ";

   cout<<endl;

   selectionSort(a, n);

   printf("\nSorted array is: \n");

   for (i = 0; i < n; i++)

   cout<< a[i] <<" ";

   return 0;

}

output

Given array is:
22 91 35 78 10 8 75 99 1 67
Sorted array is:
1 8 10 22 35 67 75 78 91 99

In the above program, selectionSort() is a function that sorts the array a[] using selection sort. There are two for loops in selectionSort(). In each iteration of the outer for loop, the minimum element in the remaining array after i is found and then interchanged with the element currently at i. This is repeated until the array is sorted.

 

 


Comments