Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create bubble_sort.c #47

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions Task2/Comp_coding/bubble_sort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include <stdio.h>

void bubbleSort(int arr[], int n) {
int temp;
int swapped;

for (int i = 0; i < n - 1; i++) {
swapped = 0; // Initialize a flag to check if any swapping occurs in this pass

// Perform a pass through the array
for (int j = 0; j < n - i - 1; j++) {
// Swap if the element found is greater than the next element
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1; // Set the flag to true to indicate a swap
}
}

// If no two elements were swapped in this pass, the array is already sorted
if (swapped == 0) {
break;
}
}
}

int main() {
int n;

printf("Enter the number of elements in the array: ");
scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Sort the array using Bubble Sort
bubbleSort(arr, n);

printf("Sorted array in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

printf("\n");

return 0;
}