Data structure and algorithm -- sorting

Posted by ernielou on Mon, 27 Dec 2021 02:51:37 +0100

Hill sorting: ① take a positive integer d1 (d1 < n) as the first increment, divide all n records into d1 groups, and put all records separated by d1 into one group, that is, for each k(k=1, 2,... d1), R[k], R[d1+k], R[2d1+k],... Into the same group, and perform direct insertion sorting in each group. Such a grouping and sorting process is called sorting;
② Take the new increment D2 < D1 and repeat the grouping and sorting operations of ①; Until the increment di=1, that is, all records are sorted in one group.

 public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] arr=new int[8];
        for (int i = 0; i <8; i++) {
            arr[i]=(int)(Math.random()*8000);
        }
        System.out.println("The initial data are:"+Arrays.toString(arr));
        Date date1=new Date();
      //  SimpleDateFormat simpleDateFormat=new SimpleDateFormat(seconds);
      //  String str1=simpleDateFormat.format(date1);
       // System.out.println("the time before Hill sorting is:" + date1);
        shellSort2(arr);
        Date date2=new Date();
      //  String str2=simpleDateFormat.format(date2);
       // System.out.println("the time after Hill sorting is:" + date2);
        }
        //Hill sort [shift]
    public static void shellSort(int[] arr){
        int temp=arr.length/2;
        int t=0;  //Temporary variable
        int j=0;
        int insertdata=0;
        int sub=0;
        int time=1;
        while(temp>0){
            for (int i = temp; i <arr.length; i++) {
                insertdata=arr[i];
                sub=i;j=i-temp;
                while(j>=0&&insertdata<=arr[j]){
                    sub=j; //Save data
                    arr[j+temp]=arr[j];
                    j-=temp;
                }
                arr[sub]=insertdata;
            }
            System.out.printf("The first%d The data of this change is:",time++);
            System.out.println(Arrays.toString(arr));
            temp=temp/2;
        }
    }
    //Hill sort [transformation]
    public static void shellSort2(int[] arr){
        int temp=arr.length/2;
        int t=0;  //Temporary variable
        int time=1;
        while(temp>0){
            for (int i = temp; i <arr.length; i++) {
                for (int j = i-temp; j >=0 ; j-=temp) {
                    if(arr[j+temp]<arr[j]){  //Direct data exchange
                        t=arr[j];
                        arr[j]=arr[j+temp];
                        arr[j+temp]=t;
                    }
                }
            }
            System.out.printf("The first%d The data of this change is:",time++);
            System.out.println(Arrays.toString(arr));
            temp=temp/2;
        }
    }


 

Bubble sort: compare the keywords of two adjacent records in turn. If the two records are in reverse order (that is, the keyword of the previous record is greater than that of the previous record), exchange them until there are no records in reverse order.

 public class BubbleSort{
 2      public static void main(String[] args){
 3          int score[] = {67, 69, 75, 87, 89, 90, 99, 100};
 4          for (int i = 0; i < score.length -1; i++){    //Sort n-1 times at most
 5              for(int j = 0 ;j < score.length - i - 1; j++){    
//Sort the current unordered area score [0... Length-i-1] (the range of j is critical, and the range is gradually narrowing)
 6                  if(score[j] < score[j + 1]){    //Swap small values to the back
 7                      int temp = score[j];
 8                      score[j] = score[j + 1];
 9                      score[j + 1] = temp;
10                  }
11              }            
12              System.out.print("The first" + (i + 1) + "Secondary sorting result:");
13              for(int a = 0; a < score.length; a++){
14                  System.out.print(score[a] + "\t");
15              }
16              System.out.println("");
17          }
18              System.out.print("Final sorting result:");
19              for(int a = 0; a < score.length; a++){
20                  System.out.print(score[a] + "\t");
21         }
22      }
23  }

Quick sort: the records to be sorted are divided into two independent parts through one-time sorting. The keywords of one part of the records are smaller than those of the other part of the records, and then the next sorting of the two parts of the records is carried out respectively to achieve the order of the whole sequence.

void Quick_Sort(int *arr, int begin, int end){
    if(begin > end)
        return;
    int tmp = arr[begin];
    int i = begin;
    int j = end;
    while(i != j){
        while(arr[j] >= tmp && j > i)
            j--;
        while(arr[i] <= tmp && j > i)
            i++;
        if(j > i){
            int t = arr[i];
            arr[i] = arr[j];
            arr[j] = t;
        }
    }
    arr[begin] = arr[i];
    arr[i] = tmp;
    Quick_Sort(arr, begin, i-1);
    Quick_Sort(arr, i+1, end);
}

The basic operation of Simple Selection Sort (also known as direct selection sort) is to select the record with the smallest keyword from n-i+1 records through the comparison of n-i keywords, and then exchange it with the ith record, i=1, 2,... n-1.

1. Working principle

Find the smallest (large) element in the unordered sequence and store it at the beginning of the sorted sequence. Then, continue to find the smallest (large) element from the remaining unordered elements and store it at the end of the sorted sequence until all elements are sorted.

2. For n elements, the time complexity is O(n^2);

3. If n is large, the efficiency will be similar to bubble sorting and unstable.

void seletSort(int a[], int len)

{

    int i, j, k;

    for (i = 0; i < len; i++)

    {

        k = i;   //Initialize the smallest tag

        for (j = i; j < len; j++)

        {

            if (a[j] < a[k])

            {

                k = j;

            }

        }

        int temp = a[i];  //Exchange value

        a[i] = a[k];

        a[k] = temp;

    }

}

Heap sorting: according to the definition of heap, heap is a complete binary tree with k1 as the root. If the nodes of the binary tree are numbered (from top to bottom, from left to right), the sequence obtained is to store the nodes of the binary tree in a sequential structure, and the heap structure is exactly the same as the sequence structure.
 

   public static void heapSort(int[] arr) {
        //1. Build large top reactor
        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            //Adjust the structure from the first non leaf node from bottom to top and from right to left
            adjustHeap(arr, i, arr.length);
        }
        //Then continue to adjust the heap, and then exchange the top element with the end element to get the second largest element. Such repeated exchange, reconstruction and exchange.
        //2. Adjust heap structure + exchange top and end elements
        for (int j = arr.length - 1; j > 0; j--) {
            swap(arr, 0, j);//Swap top and end elements
            adjustHeap(arr, 0, j);//Readjust the heap
        }
    }
    /**
     * Adjust the large top heap (only the adjustment process, which is based on the construction of the large top heap, that is, it is only called once, and the large top heap is not obtained)
     * Is to put the value of arr[i] in the appropriate position in this adjustment process.
     * @param arr    : array
     * @param i      : Index of non leaf node
     * @param length : Adjust the number of elements, and the length is gradually reduced
     */
    public static void adjustHeap(int[] arr, int i, int length) {
        int temp = arr[i];//First take out the current element i
        for (int k = i * 2 + 1; k < length; k = k * 2 + 1) {//Start from the left child of node i, that is, 2*i+1
            if (k + 1 < length && arr[k] < arr[k + 1]) {//If the left child node is smaller than the right child node, k points to the right child node
                k++;
            }
            if (arr[k] > temp) {//If the child node is larger than the parent node, assign the child node value to the parent node (no exchange)
                arr[i] = arr[k];//Assign a larger value to the current node
                i = k;//i points to k and continues the cyclic comparison
            } else {
                break;
            }
        }
        arr[i] = temp;//Put the temp value in the final position
    }
    public static void swap(int[] arr, int a, int b) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }