Find and sort of basic operations: Find a large collection of sorting algorithms

Emphasis

Search algorithm focuses master: sequential search, binary search, hash table lookup, binary sort tree search.

Sorting algorithm focuses master: bubble sort, insertion sort, merge sort, quick sort.

Sequential search

Algorithm description

Sequential search the storage structure adapted to store sequentially storing a link or a linear table.

ALGORITHM

Also known as linear sequential search to find, it belongs to disorderly search algorithm . From one end of the data structure of linear form, sequential scan, to scan sequentially the node key with a given value k is compared, if the lookup indicates equal success; If the scan end key is still not found equal to the node k, A lookup failed.

Algorithm

int sequenceSearch(int a[], int value, int len)
{
    int i;
    for(i=0; i<len; i++)
        if(a[i]==value)
            return i;
    return -1;
}

Analysis of Algorithms

When the search is successful the average search length :( assuming equal probability of each data element) ASL = 1 / n (1 + 2 + 3 + ... + n) = (n + 1) / 2; when the search is unsuccessful, it is necessary n + 1 comparisons, the time complexity is O (n); therefore, the sequential search time complexity of O (n-) .


Binary search

Algorithm description

Element must be ordered, if the disorder is sort of the first operation.

ALGORITHM

Also known as binary search, belonging to an ordered search algorithm. Compared with the first key intermediate node with a given value of k, the linear intermediate node table is divided into two sub-tables, if equal, the search is successful; if not equal, then k is determined in accordance with the comparison result of the intermediate node key Next find out which child table, so recursively until you find the look or end table does not find such a node. Note: The binary search prerequisite is the need for an orderly sequence table storage for static lookup tables, no change after a sort, binary search can get good efficiency. But the need for frequent insertion or deletion of data collection, the maintenance of orderly sequencing will bring no small amount of work, it is not recommended.

Algorithm

//二分查找,常规版
int binarySearch1(int a[], int value, int len)
{
    int low, high, mid;
    low = 0;
    high = len-1;
    while(low<=high)
    {
        mid = low+(high-low)/2;    //防止溢出
        if(a[mid]==value)
            return mid;
        if(a[mid]>value)
            high = mid-1;
        if(a[mid]<value)
            low = mid+1;
    }
    return -1;
}
 
//二分查找,递归版
int binarySearch2(int a[], int value, int low, int high)
{
    int mid = low+(high-low)/2;
    if(a[mid]==value)
        return mid;
    if(a[mid]>value)
        return BinarySearch2(a, value, low, mid-1);
    if(a[mid]<value)
        return BinarySearch2(a, value, mid+1, high);
}

Analysis of Algorithms

The worst case, the number of keywords comparison log2 (n + 1), so that the time complexity is O (log2n);


 

Bubble Sort

Algorithm description

Belonging to the class sorting exchange, stable sort

ALGORITHM

Comparing the size of two adjacent numbers, the maximum number on the right, counter i ++;

Repeat 1 continues until a [n-2] and a [n-1] where the comparison ended, the array has a maximum value in a [n-1];

The length of the array sort n minus 1, 1 and repeat the operation 2, until n is 1, sorted.

Algorithm

void bubbleSort(int* array, int length)
{
    for (int i = 0; i < length - 1; ++i)
    {
        //bool is_Swap=false;
        for (int j = 0; j < length - 1 - i; ++j)
        {
            if (array[j] > array[j + 1])
            {
                //is_Swap=true;
                int temp = array[j];
                array[j] = array[j + 1];
                Array [J + . 1 ] = TEMP;
                 / * 
                exchange may also be used as follows 
                A = A + B; 
                B = A - B; 
                A = A - B; 
                exchange may also be used as follows 
                A = A ^ B; 
                B = B A ^; 
                A ^ B = A; 
                * / 
            } 
        } 
        // IF (== is_Swap to false)
             // return; 
    } 
}

Analysis of Algorithms

The average time complexity : O (n ^ 2). The best case : if the data sequence to be sorted is positive, then the trip can be completed bubble sort, the sort of the number of comparisons is n-1 times, and does not move, the time complexity is O (n). To achieve O (n) complexity of code need to add a flag bit (Bool variable). Worst case : if the reverse sequence is the data to be sorted, the bubble sort requires n-1 times times, ni times per trip for comparison and sorting movement, i.e., comparing, and reached the maximum number of mobile: the number of comparisons = n ( n-1) / 2 = O (n ^ 2), is equal to the number of comparison times moving, so the worst time complexity is O (n ^ 2).


 

Insertion Sort

Algorithm description

 Belonging to the class of insertion sort, stable sort.

ALGORITHM

 From the second element of the array to be sorted, which was the size comparison with the previous number, and find the right position inserted until all elements have been inserted.

Algorithm

void insertSort ( int * Array, int length) 
{ 
    int I = 0 , J = 0 , TEMP = 0 ;
     for (I = . 1 ; I <length; ++ I) 
    { 
        // if the element is smaller than the previous element, is greater than all of that element after a shift,
         // until you find the element you want to insert the location and insert it. 
        IF (Array [I] <Array [I- . 1 ]) 
        { 
            TEMP = Array [I];
             for (J = I- . 1 ; TEMP <Array [J] && J> = 0 ; - J) 
            { 
                Array [J+1] = array[j];
            }
            array[j + 1] = temp;
        }
    }
}

Analysis of Algorithms

 The average time complexity : O (n ^ 2). Best case : when the recording has been ordered to be sorted, the number of time to be compared to n-1 = O (n) . Worst-case scenario : if recording is to be sorted in reverse order, the highest number of comparisons is n * (n-1) / 2 = O (n ^ 2)


Merge sort

Algorithm description

 Wider application, stable sort.

ALGORITHM

Merge sort is a typical application sub-rule of law, so that each first sequence order, then each child between the ordered sequence. The two ordered subsequences into an ordered merge list, called way merge. Step: a first ordered sequence two points, two in each region in four ...... until only one data, then each subsequence can be viewed as an ordered sequence. Then the merger, the merger is an ordered sequence of each merger,

Algorithm

 

void MergeArray(int* array, int first, int mid, int last, int* temp)
{
    //将a[first...mid]和a[mid+1...last]合并
    int i = first, j = mid + 1, k = 0;
    int lengthA = mid+1, lengthB = last+1;
    while (i < lengthA&&j < lengthB) 
    {
        if (array[i] < array[j])
            temp[k++] = array[i++];
        else
            temp[k++] = array[j++];
    }
    while (i < lengthA) 
    {
        temp[k++] = array[i++];
    }
    while (j < lengthB) 
    {
        temp[k++] = array[j++];
    }
    for (i = 0; i < k; ++i) 
    {
        array[first + i] = temp[i];
    }
}

void MergeSort(int* array, int first, int last, int* temp) 
{
    if(First> = Last)
         return ;
     int MID = (First + Last) / 2 ; 
    mergesort (Array, First, MID, TEMP); // left ordered 
    mergesort (Array, MID + . 1 , Last, TEMP); // ordered the right 
    MergeArray (Array, First, MID, Last, TEMP); // merge the two ordered subsequences 
}

Analysis of Algorithms

Mean, preferably, the worst time complexity are: O (n * log n)

Can be understood: consolidation entails O (log n) operation step, each step of the exhaust merging the ordered sequence requires O (n) operations. That certainly is the time complexity of O (n * log n).


Quick Sort

Algorithm description

 In exchange class sorting algorithm, quick drain is the fastest. The idea of ​​using divide and conquer, unstable sort.

ALGORITHM

Select an element from the n elements as a standard partition, typically selected from the first element;

The element is smaller than that on the left, greater than or equal to the element on the right side, put the intermediate element;

And then were left to repeat sequences 1 and 2, only one element, sorted in sequence until each.

Algorithm

 

// version. 1 
void the QuickSort ( int * Array, int Low, int High) 
{ 
    IF (Low> = High)
         return ;
     int left = Low;
     int right = High;
     int Key = Array [left]; // selecting a first as elements distinguishing element, of course, may be selected from the last element. 
    the while (! left = right) 
    { 
        the while (! && left = right Array [right]> key =) // right to left, the left side is smaller than the key elements into the key 
            - right; 
        Array [left] = Array [right ];
        the while (! && left = right Array [left] <= key) // left to right, is greater than the key element into the right key 
            ++ left; 
        Array [right] = Array [left]; 
    } 
    Array [left] = Key; // this time left is equal to right 

    // is divided into two ideological divide and conquer, recursive calls. 
    The QuickSort (Array, Low, left - . 1 ); 
    the QuickSort (Array, left + . 1 , High); 
}

As we all know, Partition function whether in quick sort, or in looking for this kind of problem in the K-large, has a very important position, and therefore write separately, there is a version 2.

int the Partition ( int * Array, int left, int right) 
{ 
    int Key = Array [left];
     the while (! left = right) 
    { 
        the while (! && left = right Array [right]> Key =) // from right to left, less than key elements into the key in the left 
            - right; 
        Array [left] = Array [right];
         the while (left = right && Array [left] <= key!) // left to right, the key element is greater than the discharge the right key 
            ++ left; 
        Array [right] = Array [left]; 
    } 
    Array [left] = key;
    return left;//返回区分函数
}

//快排主函数
void quicksort(int* arr, int left, int right)
{
    if(left< right)
    {
        int middle = mypartition(arr, left, right);
        quicksort(arr, left, middle-1);
        quicksort(arr, middle+1, right);
    }
}

Analysis of Algorithms

 

The average time complexity : O (n * log n) . Reason: a quick drain of the array is divided into two in the end, it is necessary to O (log n) time of this operation, each operation needs to sort n times, so that, in most cases, the time complexity is O (n * log n ). Best case : the end of each trip is sorted, each divided into two sub-file that the length is substantially equal to, the time complexity is O (n * log n). Worst-case scenario : the elements to be sorted is already sorted. After the first trip n-1 times the first comparison element remains unchanged position, and obtain a sub-sequence of n-1 element; n-2 after the second pass comparisons, the second element is positioned in the original position and to obtain a sequence comprising n-2 sub-elements, and so on, so the total number of comparisons is: n (n-1) / 2 = O (n ^ 2).


 

Guess you like

Origin www.cnblogs.com/parzulpan/p/11258491.html