C examples for Data Structure:Sort
Generates 10 random numbers and then bubble sorts them
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(){/*from w w w. j ava 2 s . co m*/ int didSwap, temp; int nums[10]; time_t t; // If you don't include this statement, it will // generate the same 10 random numbers srand(time(&t)); for (int i = 0; i < 10; i++){ nums[i] = (rand() % 99) + 1; } for (int i = 0; i < 10; i++){ printf("%d\n", nums[i]); } for (int outer = 0; outer < 9; outer++){ didSwap = 0; //Becomes 1 (true) if list is not yet ordered for (int inner = outer; inner < 10; inner++){ if (nums[inner] < nums[outer]){ temp = nums[inner]; nums[inner] = nums[outer]; nums[outer] = temp; didSwap = 1; } } if (didSwap == 0){ break; } } puts("\nafter sort:"); for (int i = 0; i < 10; i++){ printf("%d\n", nums[i]); } return(0); }