Table of Contents
show
Sorting refers to ordering data in an increasing or decreasing fashion according to some linear relationship among the data items.
Example
Selection Sort
Selection sort is a simple sorting algorithm. This sorting algorithm 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.
The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.
Program: Selection sort
#include <stdio.h>
int main()
{
int i, j, position, swap;
int arr[100],n;
printf("Enter array elements\n");
scanf("%d",&n);
printf("Enter elements \n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for (i = 0; i < (n - 1); i++) {
position = i;
for (j = i + 1; j < n; j++) {
if (arr[position] > arr[j])
position = j;
}
if (position != i) {
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
printf("The elements after sorting: \n");
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0;
}
Output
Enter array elements
5
Enter elements
2
1
4
-1
9
The elements after sorting:
-1 1 2 4 9
Views: 0