Sorting algorithm to sort a fake

Bubble sort
  Principle: To compare two adjacent elements, large elements of the right to exchange value.

  The origin of the name of the algorithm is because the smaller elements will slowly through the exchange of "float " to the top of the columns, hence the name.

Analysis of Algorithms

    The performance of bubble sort algorithm

Sort by category

Sort method

time complexity

Space complexity

stability

Complexity

Average case

Worst case

Best case

Sort exchange

Bubble Sort

O (N 2 )

O (N 2 )

O (N)

O (1)

stable

simple


Time complexity is:

   1. If our data is positive, a trip just to go to complete the order.
     The required number of comparisons C and M are the number of movements recorded reaches a minimum, namely: Cmin = n-1; Mmin = 0;
    therefore, bubble sort is the best time complexity ----- O (n).
   2. Unfortunately, if our data are in reverse order, we need to sort n-1 times.
    Each trip ni comparisons to be sorted (1≤i≤n-1), and each comparator must be moved to achieve switching times recorded recording position.
     In this case, the comparison and reached the maximum number of mobile: Bubble Sort worst time complexity is ----- O (n2).
  To sum up: the total bubble sort is the average time complexity ----- O (n2).

Algorithm stability

  Bubble sort is the little elements move it forward or backwards in the big elements. Comparison of two adjacent elements is more, also the exchange occurs between these two elements.

  Therefore, the same order before and after the element has not changed, so the bubble sort is a stable sort algorithm .

. 1  public  class the BubbleSort {
 2      public  void Sort () { . 4          int [] = ARR {12,123,3,1,0,6,4,6} ; . 8          // optimized code, if not orderly exchange represents 
9          Boolean isChange = to false ;
 10  
. 11          IF (ARR == null || arr.length <2 ) {
 12 is              return ;
 13 is          }
 14          for ( int I = 0; I <-arr.length. 1; I ++ ) {
 15              isChange = to false ;
 16              for (int j=0;j<arr.length-1-i;j++){
17                 if(arr[j]>arr[j+1]){
18                     swap(arr,j,j+1);
19                     isChange=true;
20                 }
21             }
22             if(!isChange){
23                 break;
24             }
25         }
32     }
33 
34     private void swap(int[] arr,int i, int j) {
35         arr[i]=arr[i] ^ arr[j];
36         arr[j]=arr[i] ^ arr[j];
37         arr[i]=arr[i] ^ arr[j];
38 
39     }
40 }

 

Guess you like

Origin www.cnblogs.com/loveer/p/11264968.html
Recommended