C Program to Sort a List using Bubble 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: Repeat the following steps until the list is sorted:
a. Set is_sorted to True (assume the list is sorted).
b. Iterate through the list from 0 to n-2 (i).
i. If the element at index i is greater than the element at index i+1,
swap the elements, and set is_sorted to False (the list is not sorted).
c. If is_sorted is True, break the loop (the list is sorted).
Step 5: Display the sorted list.
Step 6: 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 Bubble Sort
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
// Flag to check if any swaps were made in the current pass
int swapped = 0;
// Last 'i' elements are already in place, so we don't need to compare them again
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
swapped = 1;
}
}
// If no swaps were made in this pass, the list is already sorted
if (swapped == 0) {
break;
}
}
}
// 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");
bubbleSort(arr, size);
printList(arr, size);
return 0;
}
OUTPUT :
Enter the size of the list: 6
Enter the elements of the list:
32 15 8 76 43 5
Original list: 32 15 8 76 43 5
Sorted list: 5 8 15 32 43 76
No comments:
Post a Comment