C++ Program to Implement Sorted Array


A sorted array is an array in which each of the elements are sorted in some order such as numerical, alphabetical etc. There are many algorithms to sort a numerical array such as bubble sort, insertion sort, selection sort, merge sort, quick sort, heap sort, etc. More details about sorting the array using selection sort are given below.

The selection sort is a sorting method that yields a sorted array. It does so by repeatedly finding the smallest element in the array and interchanging it with the element at the starting of the unsorted part.

A program that implements a sorted array using selection sort is given as follows.

Example

 Live Demo

#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. This is shown below.

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;
   }
}

In the main() function, the array a[] is defined. Then the function selectionSort() is called with the array a[] and its size n. Finally, the sorted array is displayed. This is shown below.

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;
}

Updated on: 14-Sep-2023

24K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements