Sorting Algorithms

Sorting Algorigms

Finally I get time to relax and note something. Now I will review several basic algorithms and take it as a chance for reviewing c++ programming. All demenstration codes will be shown in c++.

Bubble sort

Bubble sort has the top priority in the sorting algorithms and it often occurs in the interview or examination(Perhaps the philosophy that is pretty simple).So we get start from bubble sort:

1
2
3
4
5
6
7
8
9
10
11
int arr[]= {5, 1, 2, 7, 4, 3, 6};
int length = (int) sizeof(arr)/sizeof(*arr); // get the length of array
for (int i = 0; i < length - 1; i++)
for (int j = 0; j < length - 1 - i; j++)
if (arr[j] > arr[j+ 1])
swap(arr[j],arr[j+1]);

for (i = 0; i < length; i++)
std::cout << arr[i] << ' ';
std::cout << std::endl;
return 0;

The basic idea of bubble sorting is comparing every neighboring two elements, thus the largest or smallest one will be arranged to the last one after a round. Then repeat this process until all elements in order.

Quicksort

Quick sort is a fast and efficient sorting algorithm.