Basic sorting (a) exchange sorting (bubble, fast)

  Algorithms and data structures are each advanced programmer must master. Selection of internal sorting comprises sorting, exchange sort, insertion sort, merge sort, bucket sort and radix sort. This article deals about the sort of internal sorting exchange in detail. It is called the exchange sort, because these algorithms is the main data set of continuous exchange. Sort exchange include bubble sort and quick sort.  

  Please indicate the source --http: //www.cnblogs.com/zrtqsk/p/3802583.html, thank you!

First, the tools

  In order to facilitate Ordination, here, I created a simple utility class for generating sequencing data, and output ordering content. Ordination, of course, all data is set to int type on it. as follows:

package sort;

import java.util.Arrays;
import java.util.Random;

/**
 @ClassName: SortUtil 
* @Description: Sort tools
* @author qsk
* 8:14:55 @date 2014 Nian 6 21 afternoon
 * / 
Public  class SortUtil {
     / **
     * @Title: outputArray
     * @Description: Output int type array
     * @param @param array
     * @return void
     * @throws
     */
    public static void outputArray(int[] array) {
        System.out.println(Arrays.toString(array));
    }

    /**
     * @Title: getRandomArray
     * @Description: random array obtained in the range of 100
     * @Param  @param you
     * @param @return
     * @return int[]
     * @throws
     */
    public static int[] getRandomArray(int size) {
        Random rd = new Random(System.currentTimeMillis());
        int[] array = new int[size];
        for (int i = 0; i < array.length; i++) {
            array[i] = rd.nextInt(100);
        }
        return array;
    }

    /**
    * @Title: getRandomArray 
    * @Description: length in the range 100 to obtain the array 10 is then
    * @param @return    
    * @return int[]     
    * @throws
     */
    public static int[] getRandomArray() {
        return getRandomArray(10);
    }
}

 

Second, the bubble sort

  The name bubble sort, is none, I do not know. Its principle is very simple.

  1, the principle of

  For n data records.

  Run 1: 0 element are compared in turn and 1,1 and 2,2 and 3 ... n-2 n-1 and the index of greater than found in front of the back, they are exchanged, so that trip down, the largest elements lined up last.

  Run 2: Continue to do it again in accordance with the practice of the first trip, a trip down, the second largest element lined up last.

  ......

  Thus after n-1 times comparison, switching, n-sorted data. If a trip is not exchanged, indicating already sorted, the sort can end in advance.

 

  2, the Java realization

package sort;

/**
 * 
 @ClassName: BubbleSort
 * @Description: Bubble Sort
 * @author qsk
 * 4:45:57 @date 2014 Nian 6 21 afternoon
 */
public class BubbleSort {

    public  static  void Sort ( int [] Source) {
         // before the first sort output 
        SortUtil.outputArray (Source);
         int size = source.length;
         for ( int I = 0; I <size -. 1; I ++ ) {
             Boolean isSwap = to false ;
             // every sort are from 0, size-i-1 end, since the end of each trip sorting, ordering queue will be the maximum that moves to the rightmost 
            for ( int J = 0; J <size - I -. 1; J ++ ) {
                 //
                 IF (Source [J]> Source [J +. 1 ]) {
                     int TEMP = Source [J];
                    source [j] = source [j + 1 ];
                    source [j + 1] = Temp;
                    isSwap = true;
                }
            }
            // If there is no change, on behalf of the sort has ended 
            IF (! IsSwap) {
                 BREAK ;
            }
            // Each output end of the exchange 
            SortUtil.outputArray (source);
        }
    }

    public static void main(String[] args) {
        sort (SortUtil.getRandomArray ());
    }
}

As above, the comment has been very clear with the following results:

[35, 63, 63, 24, 21, 40, 26, 22, 2, 41]
[35, 63, 24, 21, 40, 26, 22, 2, 41, 63]
[35, 24, 21, 40, 26, 22, 2, 41, 63, 63]
[24, 21, 35, 26, 22, 2, 40, 41, 63, 63]
[21, 24, 26, 22, 2, 35, 40, 41, 63, 63]
[21, 24, 22, 2, 26, 35, 40, 41, 63, 63]
[21, 22, 2, 24, 26, 35, 40, 41, 63, 63]
[21, 2, 22, 24, 26, 35, 40, 41, 63, 63]
[2, 21, 22, 24, 26, 35, 40, 41, 63, 63]

 

  3, the time complexity and stability

  Bubble sort time complexity is O (N 2 ).
  The number of columns is assumed to be sorted have number N. Traverse trip time complexity is O (N), how many times it needs to traverse? N-1 times! Thus, bubble sort time complexity is O (N 2 ).

  Bubble sort algorithm is stable , it meets the definition of a stable algorithm.
  Stability algorithms - assuming the presence of a [i] = a [j ] in the series, if the prior sorting, a [i] in a [j] the foregoing; and after sorting, a [i] is still in a [j] front. Then the sorting algorithm is stable!

 

Third, the quick sort

  Quick sort is a sorting method is very fast switching speed, but is more complicated to implement.

  1, the principle of

  For n data records.

  Data taken out from the first element as a boundary value, in the middle, small cutoff score of all the elements on the left, all the major elements of the cutoff score on the right . Then about two recursive sequences, reselect and move the boundary value. Such layers recursion continues until each element of a sub-sequence only.

  These days to see a full description of the quick sort of picture:

  10 A Practical algorithm programmer must know and explain - the first one | fast class network

(Photo Source: http: //cricode.com/2001.html)

 

  2, the Java realization

package sort;

/**
 * @ClassName: QuickSort
 * @Description: Quick Sort
 * @author qsk
 * 8:15:27 @date 2014 Nian 6 21 afternoon
 */
public class QuickSort {

    /**
    * @Title: sort 
    * @Description: sorting algorithm calls for sub-iteration
    * @param @param source    
    * @return void     
    * @throws
     */
    public static void sort(int[] source) {
        SortUtil.outputArray (source);
        subSort(source, 0, source.length - 1);
    }

    /**
    * @Title: subSort 
    * @Description: 子排序算法,可以继续迭代
    * @param @param source
    * @param @param begin
    * @param @param end    
    * @return void     
    * @throws
     */
    public static void subSort(int[] source, int begin, int end) {

        if (begin < end) {
            // 标记1从开始起,因为不包括base,而且使用前要++,所以为这个数
            int sign1 = begin;
            // 标记2从结束起,使用前要--,所以为这个数
            int sign2 = end + 1;
            // 假设第一个为base
            int base = source[begin];
            while (true) {
                // 从左向右找第一个比base大的数,用sign1标记索引
                while (source[++sign1] < base && sign1 < end) {
                    ;
                }
                // 从右到左找第一个比base小的数,用sign2标记索引
                while (source[--sign2] > base && sign2 > begin) {
                    ;
                }
                // 若此时sign1和sign2没有碰头,就交换它们
                if (sign1 < sign2) {
                    swap(source, sign1, sign2);
                    SortUtil.outputArray(source);
                    // 若已经碰头,就结束循环
                } else {
                    break;
                }
            }
            
            //将base和sign2换一下,这样,已经将原数组分成2部分,中间的那个为base
            swap(source, begin, sign2);
            SortUtil.outputArray(source);
            subSort(source, begin, sign2 - 1);
            subSort(source, sign2 + 1, end);
        }
    }

    /**
    * @Title: swap 
    * @Description: 交换数组中索引i和j处的值
    * @param @param source
    * @param @param i
    * @param @param j    
    * @return void     
    * @throws
     */
    public static void swap(int[] source, int i, int j) {
        int temp = source[i];
        source[i] = source[j];
        source[j] = temp;
    }

    public static void main(String[] args) {
        sort(SortUtil.getRandomArray());
    }
}

如上,注释已经非常清楚了,结果如下:

 

[83, 7, 11, 47, 66, 26, 85, 79, 44, 14]
[83, 7, 11, 47, 66, 26, 14, 79, 44, 85]
[44, 7, 11, 47, 66, 26, 14, 79, 83, 85]
[44, 7, 11, 14, 66, 26, 47, 79, 83, 85]
[44, 7, 11, 14, 26, 66, 47, 79, 83, 85]
[26, 7, 11, 14, 44, 66, 47, 79, 83, 85]
[14, 7, 11, 26, 44, 66, 47, 79, 83, 85]
[11, 7, 14, 26, 44, 66, 47, 79, 83, 85]
[7, 11, 14, 26, 44, 66, 47, 79, 83, 85]
[7, 11, 14, 26, 44, 47, 66, 79, 83, 85]

   3, the time complexity of the stability and quick sort of time in the worst case complexity is O (N 2 ), the average time complexity is O (N * lgN).   This sentence is well understood that: the number of columns is assumed to be sorted with a number N. Traverse a time complexity is O (N), how many times it needs to traverse? Lg least (N + 1) times, up to N times.   (01) Why is the least lg (N + 1) times? Rapid traverse is a sort of divide and conquer method used, we see it as a binary tree, which is the number required to traverse the depth of a binary tree, according to the definition of complete binary tree, its depth is at least lg (N + 1). Thus, the number of traverse is quickly sort least lg (N + 1) times.   (02) Why are most N times? This should be very simple or quick sort will be seen as a binary tree, its maximum depth is N. Therefore, the number of traversing fast read sequencing at most N times.
  


  Quick sort algorithm is not stable , it does not meet the definition of a stable algorithm.
  Stability algorithms - assuming the presence of a [i] = a [j ] in the series, if the prior sorting, a [i] in a [j] the foregoing; and after sorting, a [i] is still in a [j] front. Then the sorting algorithm is stable!
   

 

 

Reference: "The basic training of Java programmers."

   http://www.cnblogs.com/skywang12345/p/3596746.html

   http://www.cnblogs.com/skywang12345/p/3596232.html

Reproduced in: https: //www.cnblogs.com/zrtqsk/p/3802583.html

Guess you like

Origin blog.csdn.net/weixin_33850015/article/details/93248533