Bubble sort compares two adjacent numbers, switching places if they are larger or smaller. Finally the largest number (the smallest) floats to the top like a bubble
( 5 1 4 2 8 ) ( 1 5 4 2 8 ),5 > 1. ( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Since 5 is greater than 4, we swap them ( 1 4 5 2 8 ) ( 1 4 2 5 8 ), 5 is greater than 2 ( 1 4 2 5 8 ), ( 1 2 4 5 8 ), swap 2 ,4 ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 )
#include <stdio.h> int main() { int array, n, i, d, swap; printf("Enter number of elements\n"); scanf("%d", &n);/*How many numbers to sort*/ printf("Enter %d integers\n", n); for (i = 0; i < n; i++) scanf("%d", &array);/*Read n characters from the user keyboard*/ for (i = 0 ; i < ( n - 1 ); i++) { for (d = 0 ; d < n - c - 1; d++) { if (array > array[d+1]) /* Bubble sort, swapping if the number is larger than the next one */ { swap = array; array = array[d+1]; array[d+1] = swap; } } } printf("Sorted list in ascending order:\n"); for ( i = 0 ; i < n ; i++ )/*Output the sorted result*/ printf("%d\n", array); return 0; }
void bubble_sort(long list[], long n) { long i, j, t; for (i = 0 ; i < ( n - 1 ); i++) { for (j = 0 ; j < n - i - 1; j++) { if (list > list[j+1]) { /* Swapping */ t = list; list = list[j+1]; list[j+1] = t; } } } }
bubble sort function usage:
#include <stdio.h> void bubble_sort(long [], long); int main() { long array, n, i, d, swap; printf("Enter number of elements\n"); scanf("%ld", &n); printf("Enter %ld integers\n", n); for (i = 0; i < n; i++) scanf("%ld", &array); bubble_sort(array, n);/*Call the bubble sort function*/ printf("Sorted list in ascending order:\n"); for ( i = 0 ; i < n ; i++ ) printf("%ld\n", array); return 0; }