Selection sort is an in-place sorting algorithm and it works as below.
Consider an array of 'n' entries, search for the smallest entry in that array and swap it to the first position. After that, search the remaining elements(2 to n) to find the next smallest element and swap it to the second position. Continue this operation until all the elements in the array are sorted.
50 10 40 30 20
10 50 40 30 20
10 20 40 30 50
10 20 30 40 50
See Also:
Example Program For Selection Sort:
Consider an array of 'n' entries, search for the smallest entry in that array and swap it to the first position. After that, search the remaining elements(2 to n) to find the next smallest element and swap it to the second position. Continue this operation until all the elements in the array are sorted.
50 10 40 30 20
10 50 40 30 20
10 20 40 30 50
10 20 30 40 50
See Also:
C Program To Perform Insertion Sort
C Program To Perform Shell Sort
C Program To Perform Bubble Sort
C Program To Perform Quick Sort
C Program To Perform Radix Sort
C Program To Perform Selection Sort
C Program To Perform Heap Sort
C Program To Perform Merge Sort
C Program To Perform External Sorting
C Program To Perform Sorting Using Binary Search Tree
C Program To Perform Shell Sort
C Program To Perform Bubble Sort
C Program To Perform Quick Sort
C Program To Perform Radix Sort
C Program To Perform Selection Sort
C Program To Perform Heap Sort
C Program To Perform Merge Sort
C Program To Perform External Sorting
C Program To Perform Sorting Using Binary Search Tree
Example Program For Selection Sort:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *data, count, temp, i, j, min;
printf("No of elements:");
scanf("%d", &count);
data = (int *)malloc(sizeof (int) * count);
printf("Enter ur inputs:\n");
for (i = 0; i < count; i++) {
scanf("%d", &data[i]);
}
/* advance 1 position for each level of parsing */
for (i = 0; i < count - 1; i++) {
/* search for the min element */
min = i;
for (j = i + 1; j < count; j++) {
if (data[j] < data[min]) {
min = j;
}
}
/* swap min element with the current element */
if (min != i) {
temp = data[i];
data[i] = data[min];
data[min] = temp;
}
for (j = 0; j < count; j++)
printf("%-3d", data[j]);
printf("\n");
}
printf("Sorted Data:\n");
for (i = 0; i < count; i++)
printf("%-3d", data[i]);
printf("\n");
return 0;
}
Output: (C Program To Implement Selection Sort)
jp@jp-VirtualBox:$ ./a.out
No of elements:5
Enter ur inputs:
50 10 40 30 20
10 50 40 30 20
10 20 40 30 50
10 20 30 40 50
Sorted Data:
10 20 30 40 50
No of elements:5
Enter ur inputs:
50 10 40 30 20
10 50 40 30 20
10 20 40 30 50
10 20 30 40 50
Sorted Data:
10 20 30 40 50
No comments:
Post a Comment