Algorithm Basics--1. Sorting

Source: Internet
Author: User
Tags array length

Sorting algorithms

Exchange Sort class: bubble sort, quick sort

Select Sort class: Simple select Sort, heap sort

Insert Sort class: Direct insert sort, hill sort

Bubble sort

Bubble sort (Bubble sort), the basic idea for sorting is 22 to compare the keywords of small neighboring data, and if the order is reversed, it is exchanged until there are no reversed records.

There are several variations of bubble ordering, and the code for three different implementations is as follows:

Os:win | Terminal:cmder | Editor:atom |    Language:cvoid Swap (int *a, int *b) {int temp = *a;    *a = *b; *b = temp;} The easiest sort, starting from the first element, is to compare each element backwards, exchanging the smallest element, placing it in the I position//so that the sort is more useless than the comparison, of course, which is not called bubble sort void simplebubble (int array[], int Length) {for (int i = 0, i < length; i++) {for (int j = i+1; j < length; J + +) {if (Array[i] &G T            Array[j]) {Swap (&array[i],&array[j]); }}}}//from the first position, from the bottom up 22 elements to compare, judge and exchange to get the minimum value//so that the order loop determines the first position of the element void littlebubble (int array[], int length) {for (i NT i = 0; i < length; i++) {for (int j = length-1; j > i; J--) {if (Array[j] < array[j-1]) {Swap (&ar            Ray[j],&array[j-1]); }}}}//adds a flag bit isswap to indicate whether there is a reverse order or whether it has been swapped//until the sequence has no reverse order, void Bubblesort (int array[], int length) {int Isswap =    1;            for (int i = 0; i < length; i + +) {if (isswap) {isswap = 0; for (int j = length-1; j > i; j --) {if (Array[j] < array[j-1]) {Swap (&array[j],&array[j-1]);                Isswap = 1; }}}}}void Print (int array[], int length) {for (int i = 0; i < length; i++) {printf (    "%d", array[i]);    }}int Main () {int array[] = {6,5,3,1,0,2,9,8,4,7};    Bubblesort (array,10);    Print (array,10); return 0;}
Simple selection sorting

Simple Selection Sort, the basic idea is that the mark I element is the minimum subscript min to start the backward traversal comparison, constantly update the minimum subscript min, after the end of the cycle to determine whether min changes, If the change is the smallest element of the position of the I and Min position.

void SelectSort(int array[] , int length){  int min;  for(int i = 0 ; i <length ; i++){    min  = i ;  //Notice1:以第一个元素为最小开始向后遍历比较    for(int j = i+1 ; j < length ; j++){  //Notice2:j从i+1开始向后遍历      if(array[j] < array[min]){  //Notice3:每次都是array[j]与array[min]进行比较,来确定和更新最小值所在下标        min = j;      }    }    if(min != i){      Swap(&array[i] ,&array[min]);    }  }}
Direct Insert Sort

The direct insertion sort (straight insertion sort) is one of the simplest sorting algorithms, the main idea being to ensure that the elements on position 0 to i-1 position are sorted, that is, the insertion sort takes advantage of the fact that the I-position loop is sorted.

void InsertionSort(int array[] , int length ){  int i,j,temp;  //Notice1:开始以第一个数据为有序序列,从第二个数据开始排序  for(i = 1 ; i <length ; i++){    if(array[i] < array[i-1]){  //Notice2:当当前数据大于前一个时,开始向前插入      temp = array[i];  //保存此时的值,为前方较大元素空出位置      for(j = i -1 ; j>=0 && array[j] > temp ; j--){  //向前循环直至下标小于0,或者值比当前值更小        array[j+1] = array[j];  //依次后移      }      array[j+1] = temp;  //此时j位置的元素小于当前值,所以插入其后一位j+1即可    }  }}
Hill sort

The Hill sort (Shell sort) is one of the first algorithms to break the two-time barrier. The main idea is: to work by comparing the elements of a certain interval; the distance (hill increment) used for each comparison is gradually reduced as the algorithm progresses until the last order of the phase elements is compared. Thus, the hill sort is also known as narrowing the incremental sort.

void ShellSort(int array[] , int length){    int i,j,temp,gap;    int judgeCount = 0, changeCount = 0;    //Notice1:设置希尔增量序列初始值 gap = length/2 ,一直循环值gap=1进行最后一次插入排序    for(gap = length/2 ; gap >0 ; gap /=2){    //Notice2:内层嵌套一个直接插入循环        for(i = gap ; i < length ; i++ ){            judgeCount++;            if(array[i] < array[i - gap]){                temp = array[i];                for(j = i - gap ; j >= 0 && array[j] > temp ; j -=gap){                    array[j+gap] = array[j];                    changeCount++;                }                array[j+gap] = temp;            }        }    }    printf("Judge Count : %d ,Change Count : %d .\n", judgeCount,changeCount);}
Heap Sort

Heap sorting (heap sort) is a very stable algorithm, and the comparison of the average usage of the sort is only slightly less than the worst-case scenario.

void AdjustHeap(int array[] , int i , int length){  //Notice2:保存开始节点的值为temp,减少直接交换的次数  int temp = array[i];  for(int j = i*2 +1 ; j <length ; j = j*2+1){    if(j+1 < length && array[j] < array[j+1])      j++;    if(array[j] < temp )  //Notice3:循环对temp中保存的值进行比较      break;    array[i] = array[j];    i = j;  }  array[i] = temp;  //Notice4:最后在temp合适的位置上进行赋值放置}void HeapSort(int array[] ,int length){  //Notice1:首先从最后一个非页子节点开始,由右向左、由下至上开始进行最大堆的构造  for(int i = length/2 ; i >= 0 ; i --){    AdjustHeap(array , i ,length);  }  for(int i = length -1 ; i > 0 ; i --){    Swap(&array[0],&array[i]);    AdjustHeap(array, 0, i );  }}
Quick Sort

Fast sorting (Quick sort) is the fastest known sorting algorithm in practice, with an average run time of O (n log n). Fast sorting is fast because of its refined, highly optimized internal loops. The worst-case performance is O (N2), and today's highly optimized quick sorting is straightforward and easy to prove.

As with merge sort, fast sorting is also a recursive algorithm for splitting.

The basic algorithm for quickly sorting array arrays quicksort consists of the following simple four steps:

    • 1. If the array length is 0 or 1, return directly;
    • 2. Use Median3 or other methods to obtain pivot elements;
    • 3. Dividing subsets;
    • 4. Recursive call Quicksort
REF

Books:

Data structure and algorithm analysis, big liar data structure

Algorithm Basics--1. Sorting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.