Skip to main content
Search
Search This Blog
Livecodo
Pages
Home
Courses
Blog
About us
More…
Share
Get link
Facebook
X
Pinterest
Email
Other Apps
May 02, 2024
Write a c program to implement selection Sort & Bubble sort
#include
int swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } int selectionSort(int arr[], int n) { for (int i = 0; i < n-1; i++) { int min_idx = i; for (int j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; swap(&arr[min_idx], &arr[i]); } } int bubbleSort(int arr[], int n) { for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) swap(&arr[j], &arr[j+1]); } int printArray(int arr[], int size) { for (int i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } int main() { int n; printf("Enter the number of elements: "); scanf("%d", &n); int arr[n]; printf("Enter %d elements:\n", n); for (int i = 0; i < n; i++) scanf("%d", &arr[i]); printf("Original array: \n"); printArray(arr, n); selectionSort(arr, n); printf("Array sorted using Selection Sort: \n"); printArray(arr, n); bubbleSort(arr, n); printf("Array sorted using Bubble Sort: \n"); printArray(arr, n); return 0; }
Popular Posts
March 26, 2024
Dynamic Memory allocation in C
May 18, 2024
Searching and sorting Algorithm in C