Bubble sorting and binary search and for loop enhancement

Bubble sort

My understanding:

With double loops, the length of the array is as long as the outer loop is repeated. There are 10 arrays, and the outer loop will loop 10 times. Think of double loops as rows and columns. The outer loop is rows and the inner loop is columns.

For the first time, it enters the internal circulation from the external circulation. Ten elements are compared nine times.

The second time from the external circulation into the internal circulation. Compare 8 times.

The third time from the external circulation into the internal circulation. Compare 7 times.

And so on

Always put the maximum number or the minimum number you want to the last position, and then this number does not need to be compared again, so the number of inner cycles decreases in turn (array length - 1-i)

It's ok to implement transposition in inner loop.

I understand the good soil... Ha ha!

Code example

package cn.array2;

import java.util.Arrays;

public class Maopao {
    public static void main(String[] args) {
        int[]b= {5,8,7,2,6,1,5};
        sort(b);
        System.out.println(Arrays.toString(b));
    
}
    public static void sort(int[] a) {
        int temp;
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a.length-1-i; j++) {
                if(a[j]<a[j+1]) {
                    temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                }
                
            }
        }
        
    }
}

 

Binary search (sort() is the first way to sort the array when using it) (fast search speed)

 

package cn.array2;

import java.util.Arrays;
//import java.util.Arrays;

public class Array {
    public static void main(String[] args) {
        int []a= {45,8,2,38,9,8,2,22,1};
        Arrays.sort(a);                                              //To find by dichotomy, you must sort the array first
        System.out.println(Arrays.toString(a));                      //toString Follow Object Of toString What relationship?
        System.out.println("Index of the element:"+Arrays.binarySearch(a,22));//Binary search, return index value, if no negative (not found)
        Arrays.fill(a,2,4,125);                                      //Array fill,Last not filled
        System.out.println(Arrays.toString(a));
        
    }
}

Result:

Enhanced for loop (easy to traverse arrays)

package cn.array2;

public class Test {
    public static void main(String[] args) {
        int [] a= {45,4,58,1,5,56,4,45,5,4};
        for(int i=0;i<a.length;i++) {
            int m=a[i];
            System.out.print(m+"\t");
        }
        System.out.println();
        
        //Enhanced Edition for loop
        
        for(int n:a) {
            System.out.print(n+"\t");
        }
        
    }
}

Keywords: PHP Java

Added by mgs019 on Tue, 22 Oct 2019 19:05:42 +0300