Mega Code Archive

 
Categories / C / Code Snippets
 

A bubble sort on int array

#include <stdio.h> #include <stdlib.h> int main(void) { int item[100]; int x, y, t; int count; /* read in numbers */ printf("How many numbers? "); scanf("%d", &count); for(x = 0; x < count; x++) scanf("%d", &item[x]); /* now, sort them using a bubble sort */ for(x = 1; x < count; ++x) for(y = count-1; y >= x; --y) { /* compare adjacent elements */ if(item[ y - 1] > item[ y ]) { /* exchange elements */ t = item[ y - 1]; item[ y - 1] = item[ y ]; item[ y ] = t; } } /* display sorted list */ for(t=0; t<count; t++) printf("%d ", item[t]); return 0; }