Classic Algorithm--Bubble Sort (Java)

Principle: assign the larger value of the adjacent element to the right

Ideas: ① 1. Compare the first element in the collection or array with the second element, and assign the larger value to the right;

    2. Compare the second element with the third element, and assign the larger value to the right;

    .......

    (N-1). Compare the N-1th element with the Nth element, and assign the larger value to the right;

    From then on, get the maximum value of elements in the set and assign it to element N;

   ② Repeat the operation ① to get the new value of element N-1; get the new value of element N-2;

    ......

    get the value of element 2, get the value of element 1

Example:

Sort Arr[5] = {3,5,2,8,1}:

First order:

3,5,2,8,1;

3,2,5,8,1;

3,2,5,8,1;

3,2,5,1,8;

Second order:

2,3,5,1,8;

2,3,5,1,8;

2,3,1,5,8;

The third order:

2,3,1,5,8;

2,1,3,5,8;

Fourth order:

1,2,3,5,8;

 

It can be seen that: N numbers are to be sorted, and a total of N-1 sorting is performed, and the number of sorting times for each i is (Ni) times, so a double loop statement can be used, the outer layer controls how many times the loop is, and the inner layer controls each The number of cycles of the trip, that is:

for(i = 0; i<arr.length-1;i++){//How many times the outer control is sorted

  for(j = 0; j<arr.length-1-i;j++){//The inner layer controls how many times to judge the size of adjacent elements for each sorting

    if(arr[j]>arr[j+1]){

      temp = arr[j];

      arr[j] = arr[j+1];

      arr[j+1] = temp;

    }

  }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325111654&siteId=291194637