Skip to content

Instantly share code, notes, and snippets.

@joshkautz
Created March 2, 2016 18:52
Show Gist options
  • Save joshkautz/9c1b999720885e620d6a to your computer and use it in GitHub Desktop.
Save joshkautz/9c1b999720885e620d6a to your computer and use it in GitHub Desktop.
C implementation of the Bubble Sort algorithm, which repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order.
#include<stdio.h>
int main() {
int a[50], n, i, j, temp = 0;
printf("Enter how many elements you want:\n");
scanf("%d", &n);
printf("\nEnter the %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("\nThe given array is:\n[");
for (i = 0; i < n; i++) {
if(i+1==n) printf("%d]", a[i]);
else printf("%d, ", a[i]);
}
if(n==0) printf("]");
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("\n\nThe sorted array using Bubble sort is:\n[");
for (i = 0; i < n; i++) {
if(i+1==n) printf("%d]\n", a[i]);
else printf("%d, ", a[i]);
}
if(n==0) printf("]\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment