Several sorting and binary search methods

  1. Recursive binary search
  2. Bubble Sort
  3. Selection Sort
  4. Insertion Sort
  5. Merge sort
  6. Quick Sort

1, recursive binary search

 

Thought :

Use binary search prerequisite of array elements must already be sorted.

 

Code:

public static int binarySearch(int[] list, int key){
        return binarySearch(list, key, 0, list.length - 1);
    }
    public static int binarySearch(int[] list, int key , int low, int high){
        //没有查找到
        if(low > high)
            return - low - 1;
        
        int mid = (low + high) / 2;
        if(key < list[mid]){
            return binarySearch(list, key, low, mid - 1);
        }else if(key == list[mid]){
            return mid;
        }else{
            return binarySearch(list, key, mid + 1, high);
        }
    }

 

2, bubble sort

Animation: http://liveexample.pearsoncmg.com/dsanimation/BubbleSortNeweBook.html

Ideas :

Sequentially comparing adjacent two numbers, the numbers are placed ahead of large numbers on the back .

I.e. the first pass: First, a first comparator and a second number, the decimal place before, after the release of large numbers. Before then compare the second number and a third number, the decimal place, the release of large numbers, so ...... continued until the last two numbers compare, the decimal place before, after the release of large numbers. Trip Repeat steps until all the sort is complete.

After the first pass completion of the comparison, the last digit must be the biggest of a number of the array , so the second trip when comparing the last number is not involved in the comparison;

After the second pass completion of the comparison, the penultimate number, must be the second largest number in the array , so the third trip when comparing the last two numbers do not participate in the comparison;

And so on, each pass number of comparisons 1;

……

Code:

public  static  void bubbleSort ( int [] Array) { 

        // optimization: If switching does not occur in a traversal, then it is not then the next time through, since all the elements have been sorted 
        Boolean needNextPass = to true ; 

        // array.length-1 traversal need 
        for ( int k =. 1; k <array.length && needNextPass; k ++ ) { 

            needNextPass = to false ; // assumed not required for the next traversal 

            // before the k-th traversal processing array.length -k number 
            for ( int I = 0; I <be array.length -. 1; I ++ ) {
                 // sequentially comparing two adjacent elements 
                IF (Array [I]> Array [I +. 1]) {
                     // exchange 
                    int TEMP = Array [I]; 
                    Array [I] = Array [I +. 1 ]; 
                    Array [I +. 1] = TEMP; 

                    needNextPass = to true ;   // needed for the next traverse 
                } 
            } 
        } 
    }

 

3. Select the sort

Animation: http://liveexample.pearsoncmg.com/dsanimation/SelectionSortNeweBook.html

Ideas :

To find the minimum number of the array, and the number thereof, and a first exchange;

Then find the smallest number from the remaining numbers, and the second exchange;

...... go on indefinitely, until a remaining number (is a recursive process)

Code:

// main routine executed when an initial SelectionSort (Array, 0, be array.length -. 1) 

public  static  void SelectionSort ( Double [] Array, int Low, int High) {
         IF (Low < High) {
             int indexOfMin = Low;     // superscript minimum number 
            Double min = Array [Low]; // minimum number
             // find the minimum number and minimum number subscript min indexOfMin 
            for ( int I = Low +. 1; I <= High; I ++ ) {
                 IF (Array [ I] < min) { 
                    min =  Array [I];
                    indexOfMin = I; 
                } 
            } 
            // switching element and a first low min 
            Array [indexOfMin] = Array [low]; 
            Array [low] = min; 
            
            // recursive 
            SelectionSort (Array, low +. 1 , High); 
        } 
    }

 

4, insertion sort

Animation: http://liveexample.pearsoncmg.com/dsanimation/InsertionSortNeweBook.html

Ideas :

Repeating element into a new sorted by the linear table, until the entire linear table sorted.

[0,1,4,6,3]

We need to do from a [1] beginning, as to why is not a [0]. a [0] until no element to compare with a [0]. We insert a [1], this time we need to traverse a [1] and all the elements of a previous [1] and compared. Setting a variable j, for recording a first ratio of a [1] subscript that element of the light elements, i.e. a [1] to be inserted position, this time out of the loop, and did not find a ratio of a [1] after a big shift elements, it is necessary to make this element. And so on until the last of the algorithm of the entire array.

Code:

public  static  void insertionSortt ( int [] Array) {
         // from a [1] starts 
        for ( int I =. 1; I <be array.length; I ++ ) {
             int currentElement = Array [I];
             int J; // tag element to move to a position
             // first determine a number of front currentElement, if you want to move, and then moved in front of a determined number, or until it is determined to have no need to move to a determination List [0] 
            for (J = I -. 1; J> Array && 0 = [J]> currentElement; J, ) {
                 // the number in front of a rearward movement of a currentElement 
                Array [J +. 1] = Array [J]; 
            } 
            Array [J +. 1] = currentElement;
        }
    }

 

5, merge sort

Animation: http://liveexample.pearsoncmg.com/dsanimation/MergeSortNeweBook.html

thought:

Using the method of divide and rule to sort the array. The array is divided into two halves, each part of recursively applying merge sort. After the two parts are sorted, they are merged.

Code:

public  static  void mergesort ( int [] Array) {
         IF (be array.length>. 1 ) {
             // create a temporary array to store half of the front element firstHalf 
            int [] = firstHalf new new  int [be array.length / 2 ]; 
            System.arraycopy ( List, 0, firstHalf, 0, be array.length / 2 );
             // recursive 
            mergesort (firstHalf); 

            // Create a temporary storage array secondHalf rear half element 
            int lengthOfSecondHalf be array.length = - be array.length / 2 ;
             int [] = secondHalf new new  int [lengthOfSecondHalf];
            System.arraycopy (array, be array.length / 2, secondHalf, 0 , 
                    lengthOfSecondHalf); 
            // recursive 
            mergesort (secondHalf); 

            // merged into the original array of array 
            Merge (firstHalf, secondHalf, array); 
        } 
    } 

    / ** merge * / 
    public  static  void Merge ( int [] array1, int [] array2, int [] TEMP) {
         / * 
         * merge two ordered arrays array1, array2 a temporary array temp. 
         * Current1 and current2 pointing array1 and array2 current element to be considered, the comparison is repeated in the current element array1 and array2, and a smaller one of the elements to the temp.
         * If the smaller elements of array1, current1 increase 1; if the small element array2, current2 1 increases. 
         * Finally array2 array1 or a residual element will not move, it will be copied directly into the temp.
         * / 
        Int current1 = 0; // current element to be considered in array1 
        int current2 = 0; // current element to be considered array2 
        int current3 = 0; // this temp elements to be considered in 

        the while (current1 <array1. && current2 length < array2.length) {
             // If the smaller elements of array1, current1 increase. 1 
            IF (array1 [current1] < array2 [current2]) 
                TEMP [current3 ++] = array1 [current1 ++ ];
             // if more small elements in array2, current2 increase 1 
            the else 
                TEMP [current3 ++] = array2 [current2 ++ ]; 
        } 

        the while (current1 < array1.length)
            temp[current3++] = array1[current1++];

        while (current2 < array2.length)
            temp[current3++] = array2[current2++];
    }

 

6, Quick Sort

Animation: http://liveexample.pearsoncmg.com/dsanimation/QuickSortNeweBook.html

Thought :

Selecting a reference element (Pivot) in the array, the array is divided into two portions, so that all the elements are less than or equal Pivot first portion, a second portion of all the elements are larger than the pivot.

Quicksort algorithm is applied recursively to the first portion and second portion of the quick sort algorithm applied recursively.

 

Code:

// main input quickSort (array, 0, array.length - 1); begin 

public  static  void QUICKSORT ( int [] Array, int First, int Last) {
         IF (Last> First) {
             // the reference element is placed to the correct position, is obtained at a reference element subscript 
            int pivotIndex = Partition (Array, First, Last); 
            QUICKSORT (Array, 0, pivotIndex -. 1 ); 
            QUICKSORT (Array, pivotIndex +. 1 , Last); 
        } 
    } 
    / ** the after standard returned to the reference element to the reference element is placed at the correct location * / 
    public  static  int Partition (int [] Array, int First, int Last) {
         // the first element of the array as a reference element 
        int Pivot = Array [First];
         // Initially, low to sub-elements in the second array 
        int Low = First + 1 ;
         // initial condition, pointing to the last element High subarray 
        int High = last; 
        
        the while (High> Low) {
             // Find the first element is greater than the reference element from the left, if the array [low] <= pivot, skip, continue to look for a next, i.e. ++ Low 
            the while (Low <= High && Array [Low] <= Pivot) { 
                Low ++ ; 
            } 
            //From the right to find the first element is less than equal to the reference element, if the array [high]> pivot, skip, continue to look for a next, i.e. high-- 
            the while (Low <= High && Array [High]> Pivot) { 
                High - ; 
            } 
            // exchange after finding 
            IF (High> Low) {
                 int TEMP = Array [Low]; 
                Array [Low] = List [High]; 
                Array [High] = ; TEMP 
            } 
        } 
        // when high low < the search ends, the first elements starting from the right looking Pivot less, i.e., less than or equal list [first], and after finding the reference element exchange 
        the while (High> first && Array [High]> Pivot) { 
            High - ; 
        }
        if(pivot > array[high]){
            array[first] = array[high];
            array[high] = pivot;
            return high;
        }else{
            return first;
        }
            
    }

 

Guess you like

Origin www.cnblogs.com/toria/p/sort.html