Question about the number of sorting calculations in an array

No nonsense, go directly to the code.

1. Get the largest of the 5 numbers:

int[] score = {66,77,88,65,88};
int max = score[0];
for(int i=0;i<score.length-1;i++){
  if(max<score[i+1]){
    max = score[i+1];
  }
}

From this, it can be seen that the total number of calculations is

count 2 3 4 5 ... n

Number of calculations 1 2 3 4 ... n-1

The minimum number of times is the same.

 

2. Arrange the 6 numbers from small to large: (bubbling)

int[] a = { 55, 45, 23, 444, 313, 112 };
int c;
int count = 0;
for (int i = 1; i < a.length ; i++) {
  for (int j = 0; j < a.length-i; j++) {
    if (a[j] > a[j + 1]) {
      c = a[j + 1];
      a[j + 1] = a[j];
      a[j] = c;
    }
    count++;
  }
}
for (int i = 0; i < a.length; i++) {
  System.out.println(a[i] + "==" + count+"==="+a.length);
}

output:

---------------------

23==15===6
45==15===6
55==15===6
112==15===6
313==15===6
444==15===6

---------------------

Bubble Analysis:

c = a[j + 1];
a[j + 1] = a[j];
a[j] = c;

The meaning of variable C is to store a[j+1] and put a[j] after replacement.

(Don't take offense when you draw a picture)

The number of exchanges of bubbling is, (5, 4, 3, 2, 1)

 The purpose of completing the inner for loop each time is to put the largest number at the end and remove it in the next loop, so the number of times is decreased by one.

Guess you like

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