C++ examples for Data Structure:Sort
Uses bubble sort to sort an integer array
#include <cstdlib> #include <iostream> #include <ctime> const int limit = 10; int main(int argc, const char *argv[]) { srand(time(0));//from w w w. ja v a 2 s.c o m int n[limit] = {}; // randomise elements of n for (int i = 0; i < limit; ++i) { n[i] = rand() % 100; } std::cout << "Unsorted array n: " << std::endl; // print unsorted array for (int i = 0; i < limit; ++i) { std::cout << n[i] << std::endl; } // BUBBLE SORT for (int i = 0; i < limit - 1; ++i) { for (int j = 0; j < limit - 1; ++j) { if (n[j] > n[j + 1]) { int temp = n[j]; n[j] = n[j + 1]; n[j + 1] = temp; } } } for (int i = 0; i < limit; ++i) { std::cout << n[i] << std::endl; } return 0; }