Graphical Algorithm--Sorting Algorithm

Table of contents

1. Bubble sort algorithm

2. Selection sort algorithm

3. Insertion sort algorithm

4. Hill sorting algorithm

5. Merge sort algorithm

6. Quick sort algorithm


1. Bubble sort algorithm

Principle explanation:

  1. Starting from the first element in the array to be sorted, compare the size of the current element and its next adjacent element in sequence.
  2. If the current element is larger than the adjacent element, the two elements are swapped, bubbling the larger element backwards.
  3. Continue to compare adjacent elements and repeat the above steps until the entire array is traversed.
  4. After a round of traversal is complete, the largest element will be sorted last.
  5. Repeat the above steps, and each traversal will bubble the largest element among the elements to be sorted to the correct position until all elements are sorted.

 Traditional Bubble Sort Algorithm

package Sort.Bubble;

import java.util.Arrays;

public class javaDemo {
    public static void main(String[] args) {
        int nums[] = new int[]{1,4,36,7,42,2,12,5,2};
        int temp;
//        冒泡算法
        for (int i=0;i< nums.length-1;i++){
            for (int j=0;j< nums.length-i-1;j++){
                if (nums[j]>nums[j+1]){
                    temp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(nums));
    }
}

The traditional sorting algorithm has a disadvantage, that is, it will be executed n(n-1)/2 times regardless of whether the data has been sorted or not, and if the concept of sentry is added to modify the bubble sorting algorithm, the execution efficiency of the program can be improved

The result of the array that is almost sorted by traditional bubbling execution is as follows:

It can be seen that the sorting has been done in the second round, but the traversal is still going on, so a sentry (flag) judgment function is added. In the third round, if there is no element to exchange, it will directly exit the sorting.

Improved Bubble Sort

package Sort.Bubble;

import java.util.Arrays;

public class Sentry {
    public static void main(String[] args) {
        int num[] = new int[]{1,4,5,2,7,8,9};
        int flag;
        int temp;
        for (int i= num.length-1;i>0;i--){
            flag = 0;
//            如果发生了交换则不跳出
            for (int j=0;j<i-1;j++){
                if (num[j]>num[j+1]){
                 temp = num[j];
                 num[j] = num[j+1];
                 num[j+1] = temp;
                 flag ++;
                }
            }
//            如果从头遍历结束都没有交换则直接退出
            if (flag == 0){
                break;
            }
            System.out.println("第"+(num.length-i)+"轮排序结果为"+ Arrays.toString(num));
        }
    }
}

 Analysis of Algorithms:

  • The worst case time complexity of the bubble sort algorithm is O(n^2)
  • In the best case time complexity is O(n)

2. Selection sort algorithm

Principle explanation: 

  1. Traverse the array to be sorted, using the first element as the current minimum value.
  2. Find the smallest element from among the elements after the current position, and record its position.
  3. If an element smaller than the current minimum is found, update the element's position to the position of the current minimum.
  4. After traversing the entire array, exchange the minimum value with the element at the current position.
  5. Continue to repeat the above steps from the next position until the entire array is traversed.

case code

package Sort.Chose.chose;

import java.util.Arrays;

public class javaDemo {
    public static void main(String[] args) {
        int nums[] = new int[]{1,2,4,2,3,51,12,6,2};
        int min;
        int index;
        int temp;
        for (int i=0;i< nums.length-1;i++){
//            每一轮初始化最小值与最小值下角标
            min = nums[i];
            index = i;
            for (int j=i+1;j< nums.length;j++){
                if (min>nums[j]){
                    min = nums[j];
                    index = j;
                }
            }
             temp = nums[i];
            nums[i] = min;
            nums[index] = temp;
        }
        System.out.println(Arrays.toString(nums));
    }
}

 Analysis of Algorithms:

  • The time complexity of the bubble sort algorithm is O(n^2) no matter in the worst case or the best case

3. Insertion sort algorithm

 Principle explanation:

  1. Divide an array into sorted and unsorted parts. Initially, the first element is considered sorted and the rest are considered unsorted.
  2. Selects the first element from the unsorted part and compares it with the elements in the sorted part in turn.
  3. If the selected element is smaller than an element in the sorted part, the element is inserted in the correct position, and the element in the sorted part is shifted back one bit.
  4. Repeat the above steps to insert each element of the unsorted part into the correct position of the sorted part one by one.
  5. Sorting is complete when all elements have been inserted, that is, the unsorted part is empty.

case code  

package Sort.InsertSort;

import java.util.Arrays;

public class javaDemo {
    public static void main(String[] args) {
        int nums[] = new int[]{4,1,5,2,6,7,2};
        int temp;
        for (int i=0;i< nums.length;i++){
            for (int j=0;j<i;j++){
                if (nums[i]<nums[j]){
                    temp = nums[j];
                    nums[j] = nums[i];
                    nums[i] = temp;
                }
            }
            System.out.println("第"+(i+1)+"轮排序结果为"+ Arrays.toString(nums));
        }
    }
}

Analysis of Algorithms:

  • The worst case time complexity of the bubble sort algorithm is O(n^2)
  • In the best case time complexity is O(n)

4. Hill sorting algorithm

  Principle explanation:

  1. First, an incremental gap is chosen, usually half the length of the array as the initial increment.
  2. Groups the array by increment and sorts each group using the insertion sort algorithm.
  3. Gradually reduce the increment and repeat the above steps until the increment is 1.
  4. Finally sort the entire array one last time using insertion sort with an increment of 1

Case code:

package Sort.Shell;

import java.util.Arrays;

public class ShellSort {
    public static void main(String[] args) {
        int[] arr = {9, 5, 2, 7, 1, 8, 3, 6, 4};
        int n = arr.length;

        // 定义增量序列
        int[] increments = {5, 3, 1};
        System.out.println("原始数组顺序为"+Arrays.toString(arr));
        // 遍历增量序列
        for (int increment : increments) {

            // 对每个增量进行插入排序
            for (int i = increment; i < n; i++) {
                int temp = arr[i];
                int j = i;
                // 在当前增量下,对子序列进行插入排序
                while (j >= increment && arr[j - increment] > temp) {
                    arr[j] = arr[j - increment];
                    j -= increment;
                }
                arr[j] = temp;
                System.out.println("当前增量为"+increment+",当前数组为:"+Arrays.toString(arr));
            }

        }
    }
}

Analysis of Algorithms:

  • The time complexity of the Hill sort algorithm is O(n^3/2) no matter in the worst case or the best case
  • Space optimal solution

5. Merge sort algorithm

   Principle explanation:

  1. Recursively split the array to be sorted into two subarrays until each subarray has only one element.
  2. Perform a merge operation on each sub-array, merging two ordered sub-arrays into an ordered array.
  3. Repeat the above steps until all the sub-arrays are merged into a complete sorted array.

Case code:

package Sort.MergeSort;

import java.util.Arrays;

public class mergeSort {
    public static void mergeSort(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return;
        }
        int[] temp = new int[arr.length];
        mergeSort(arr, 0, arr.length - 1, temp);
    }

    private static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = left + (right - left) / 2;
            mergeSort(arr, left, mid, temp); // 递归排序左半部分
            mergeSort(arr, mid + 1, right, temp); // 递归排序右半部分
            merge(arr, left, mid, right, temp); // 合并左右两个有序数组
        }
        System.out.println("当前顺序为"+Arrays.toString(arr));
    }

    private static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left; // 左半部分起始索引
        int j = mid + 1; // 右半部分起始索引
        int k = 0; // 临时数组索引

        // 将左右两个有序数组按顺序合并到temp数组中
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[k++] = arr[i++];
            } else {
                temp[k++] = arr[j++];
            }
        }

        // 处理剩余的元素
        while (i <= mid) {
            temp[k++] = arr[i++];
        }
        while (j <= right) {
            temp[k++] = arr[j++];
        }

        // 将临时数组的元素拷贝回原数组
        for (i = 0; i < k; i++) {
            arr[left + i] = temp[i];
        }
    }
    public static void main(String[] args) {
        int[] arr = {9, 5, 2, 7, 1, 8, 3, 6, 4};
        System.out.println("原始数组:"+ Arrays.toString(arr));
        mergeSort(arr);
    }
}

Analysis of Algorithms:

  • The time complexity of the merge sort algorithm is O(nlogn) in both the worst case and the best case

6. Quick sort algorithm

   Principle explanation:

  1. Choose a pivot element (usually the first or last element of the array) as a reference point.
  2. Divide the array to be sorted into two subarrays, one of which has elements less than or equal to the reference element, and the other subarray has elements greater than the reference element.
  3. Repeat the above steps for the two sub-arrays respectively, and perform quick sorting recursively.
  4. The recursion terminates when the length of the subarray is 1 or 0.
  5. Merge the sorted sub-arrays to get a complete sorted array.

Case code:

package Sort.Quick;

import java.util.Arrays;

public class QuickSort {
    public static void quickSort(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return;
        }
        quickSort(arr, 0, arr.length - 1);
    }

    private static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pivotIndex = partition(arr, low, high); // 将数组划分为两部分,返回中轴元素的索引
            quickSort(arr, low, pivotIndex - 1); // 递归排序左半部分
            quickSort(arr, pivotIndex + 1, high); // 递归排序右半部分
        }
        System.out.println("当前数组为"+Arrays.toString(arr));
    }

    private static int partition(int[] arr, int low, int high) {
        int pivot = arr[low]; // 选择第一个元素作为中轴元素
        int left = low;
        int right = high;

        while (left < right) {
            // 从右向左找第一个小于等于中轴元素的位置
            while (left < right && arr[right] >= pivot) {
                right--;
            }
            if (left < right) {
                arr[left] = arr[right];
                left++;
            }

            // 从左向右找第一个大于中轴元素的位置
            while (left < right && arr[left] <= pivot) {
                left++;
            }
            if (left < right) {
                arr[right] = arr[left];
                right--;
            }
        }

        arr[left] = pivot; // 将中轴元素放置到最终位置
        return left; // 返回中轴元素的索引
    }

    public static void main(String[] args) {
        int[] arr = {9, 5, 2, 7, 1, 8, 3, 6, 4};

        System.out.printf("原始数组:");
        System.out.println(Arrays.toString(arr));
        quickSort(arr);
    }
}

 Analysis of Algorithms:

  • The time complexity of the quick sort algorithm in the worst case is O(nlog2n)
  • In the best case time complexity is O(n)
  • Recognized as the best sorting algorithm

Guess you like

Origin blog.csdn.net/dogxixi/article/details/132350733