9. C Program to Sort a List using Selection Sort Technique
ALGORITHM :
Step 1: Start
Step 2: Input the list of elements (my_list).
Step 3: Get the number of elements in the list (n).
Step 4: Iterate from 0 to n-2 (i).
Step 5: Set min_index to i.
Step 6: Iterate from i+1 to n-1 (j).
Step 7: If the element at index j is less than the element at min_index, update min_index to j.
Step 8: Swap the elements at indices i and min_index.
Step 9: Continue the loop until all elements are sorted.
Step 10: Display the sorted list.
Step 11: End
SOURCE CODE :
#include <stdio.h>
// Function to swap two elements in the list
void swap(int arr[], int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
// Function to perform Selection Sort
void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
int min_index = i;
// Find the minimum element in the unsorted part of the list
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
// Swap the found minimum element with the first element of the unsorted part
swap(arr, i, min_index);
}
}
// Function to print the list
void printList(int arr[], int size) {
printf("Sorted list: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int size;
printf("Enter the size of the list: ");
scanf("%d", &size);
int arr[size];
printf("Enter the elements of the list:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("Original list: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
selectionSort(arr, size);
printList(arr, size);
return 0;
}
OUTPUT :
Enter the size of the list: 5
Enter the elements of the list:
64 34 25 12 22
Original list: 64 34 25 12 22
Sorted list: 12 22 25 34 64
No comments:
Post a Comment