Java排序算法是什么及怎么实现

发布时间:2022-08-30 14:14:05 作者:iii
来源:亿速云 阅读:134

Java排序算法是什么及怎么实现

排序算法是计算机科学中最基本、最重要的算法之一。排序算法的目的是将一组数据按照特定的顺序进行排列,以便于后续的查找、统计和分析。Java作为一种广泛使用的编程语言,提供了多种排序算法的实现方式。本文将详细介绍Java中常见的排序算法及其实现方法。

1. 排序算法的基本概念

排序算法可以分为两大类:比较排序非比较排序

排序算法的性能通常通过时间复杂度空间复杂度来衡量。时间复杂度表示算法执行所需的时间,空间复杂度表示算法执行所需的内存空间。

2. 常见的排序算法及其实现

2.1 冒泡排序(Bubble Sort)

冒泡排序是一种简单的排序算法。它重复地遍历要排序的列表,比较相邻的元素并交换它们的位置,直到列表有序。

2.1.1 算法步骤

  1. 从列表的第一个元素开始,比较相邻的两个元素。
  2. 如果前一个元素大于后一个元素,交换它们的位置。
  3. 重复上述步骤,直到列表有序。

2.1.2 Java实现

public class BubbleSort {
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // 交换arr[j]和arr[j+1]
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};
        bubbleSort(arr);
        System.out.println("排序后的数组:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

2.1.3 时间复杂度

2.2 选择排序(Selection Sort)

选择排序是一种简单直观的排序算法。它的工作原理是每次从未排序的部分中选择最小(或最大)的元素,放到已排序部分的末尾。

2.2.1 算法步骤

  1. 在未排序序列中找到最小(或最大)的元素,存放到排序序列的起始位置。
  2. 从剩余未排序元素中继续寻找最小(或最大)元素,放到已排序序列的末尾。
  3. 重复上述步骤,直到所有元素均排序完毕。

2.2.2 Java实现

public class SelectionSort {
    public static void selectionSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            // 交换arr[i]和arr[minIndex]
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }

    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        selectionSort(arr);
        System.out.println("排序后的数组:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

2.2.3 时间复杂度

2.3 插入排序(Insertion Sort)

插入排序是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。

2.3.1 算法步骤

  1. 从第一个元素开始,该元素可以认为已经被排序。
  2. 取出下一个元素,在已经排序的元素序列中从后向前扫描。
  3. 如果该元素(已排序)大于新元素,将该元素移到下一位置。
  4. 重复步骤3,直到找到已排序的元素小于或等于新元素的位置。
  5. 将新元素插入到该位置后。
  6. 重复步骤2~5,直到所有元素均排序完毕。

2.3.2 Java实现

public class InsertionSort {
    public static void insertionSort(int[] arr) {
        int n = arr.length;
        for (int i = 1; i < n; i++) {
            int key = arr[i];
            int j = i - 1;
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }

    public static void main(String[] args) {
        int[] arr = {12, 11, 13, 5, 6};
        insertionSort(arr);
        System.out.println("排序后的数组:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

2.3.3 时间复杂度

2.4 归并排序(Merge Sort)

归并排序是一种分治算法。它将列表分成两个子列表,分别对子列表进行排序,然后将排序后的子列表合并成一个有序列表。

2.4.1 算法步骤

  1. 将列表分成两个子列表,分别对子列表进行排序。
  2. 将排序后的子列表合并成一个有序列表。

2.4.2 Java实现

public class MergeSort {
    public static void mergeSort(int[] arr, int left, int right) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(arr, left, mid);
            mergeSort(arr, mid + 1, right);
            merge(arr, left, mid, right);
        }
    }

    public static void merge(int[] arr, int left, int mid, int right) {
        int n1 = mid - left + 1;
        int n2 = right - mid;

        int[] L = new int[n1];
        int[] R = new int[n2];

        for (int i = 0; i < n1; i++) {
            L[i] = arr[left + i];
        }
        for (int j = 0; j < n2; j++) {
            R[j] = arr[mid + 1 + j];
        }

        int i = 0, j = 0;
        int k = left;
        while (i < n1 && j < n2) {
            if (L[i] <= R[j]) {
                arr[k] = L[i];
                i++;
            } else {
                arr[k] = R[j];
                j++;
            }
            k++;
        }

        while (i < n1) {
            arr[k] = L[i];
            i++;
            k++;
        }

        while (j < n2) {
            arr[k] = R[j];
            j++;
            k++;
        }
    }

    public static void main(String[] args) {
        int[] arr = {12, 11, 13, 5, 6, 7};
        mergeSort(arr, 0, arr.length - 1);
        System.out.println("排序后的数组:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

2.4.3 时间复杂度

2.5 快速排序(Quick Sort)

快速排序是一种分治算法。它通过选择一个“基准”元素,将列表分成两个子列表,分别对子列表进行排序。

2.5.1 算法步骤

  1. 选择一个基准元素。
  2. 将列表分成两个子列表,一个子列表中的元素都小于基准元素,另一个子列表中的元素都大于基准元素。
  3. 对子列表递归地应用快速排序。

2.5.2 Java实现

public class QuickSort {
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pi = partition(arr, low, high);
            quickSort(arr, low, pi - 1);
            quickSort(arr, pi + 1, high);
        }
    }

    public static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];
        int i = (low - 1);
        for (int j = low; j < high; j++) {
            if (arr[j] < pivot) {
                i++;
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;
        return i + 1;
    }

    public static void main(String[] args) {
        int[] arr = {10, 7, 8, 9, 1, 5};
        quickSort(arr, 0, arr.length - 1);
        System.out.println("排序后的数组:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

2.5.3 时间复杂度

2.6 堆排序(Heap Sort)

堆排序是一种基于二叉堆数据结构的排序算法。它通过构建一个最大堆(或最小堆),然后将堆顶元素与最后一个元素交换,再调整堆,重复这个过程直到列表有序。

2.6.1 算法步骤

  1. 构建一个最大堆(或最小堆)。
  2. 将堆顶元素与最后一个元素交换。
  3. 调整堆,使其满足堆的性质。
  4. 重复步骤2~3,直到列表有序。

2.6.2 Java实现

public class HeapSort {
    public static void heapSort(int[] arr) {
        int n = arr.length;

        // 构建最大堆
        for (int i = n / 2 - 1; i >= 0; i--) {
            heapify(arr, n, i);
        }

        // 逐个提取元素
        for (int i = n - 1; i > 0; i--) {
            // 交换堆顶元素和最后一个元素
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // 调整堆
            heapify(arr, i, 0);
        }
    }

    public static void heapify(int[] arr, int n, int i) {
        int largest = i; // 初始化最大元素为根节点
        int left = 2 * i + 1; // 左子节点
        int right = 2 * i + 2; // 右子节点

        // 如果左子节点大于根节点
        if (left < n && arr[left] > arr[largest]) {
            largest = left;
        }

        // 如果右子节点大于当前最大元素
        if (right < n && arr[right] > arr[largest]) {
            largest = right;
        }

        // 如果最大元素不是根节点
        if (largest != i) {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;

            // 递归调整受影响的子树
            heapify(arr, n, largest);
        }
    }

    public static void main(String[] args) {
        int[] arr = {12, 11, 13, 5, 6, 7};
        heapSort(arr);
        System.out.println("排序后的数组:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

2.6.3 时间复杂度

2.7 计数排序(Counting Sort)

计数排序是一种非比较排序算法。它通过统计每个元素的出现次数,然后根据统计结果将元素放回原列表。

2.7.1 算法步骤

  1. 统计每个元素的出现次数。
  2. 根据统计结果将元素放回原列表。

2.7.2 Java实现

public class CountingSort {
    public static void countingSort(int[] arr) {
        int n = arr.length;
        int max = Arrays.stream(arr).max().getAsInt();
        int[] count = new int[max + 1];

        // 统计每个元素的出现次数
        for (int i = 0; i < n; i++) {
            count[arr[i]]++;
        }

        // 将统计结果放回原列表
        int index = 0;
        for (int i = 0; i <= max; i++) {
            while (count[i] > 0) {
                arr[index++] = i;
                count[i]--;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {4, 2, 2, 8, 3, 3, 1};
        countingSort(arr);
        System.out.println("排序后的数组:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

2.7.3 时间复杂度

2.8 基数排序(Radix Sort)

基数排序是一种非比较排序算法。它通过将整数按位数切割成不同的数字,然后按每个位数分别进行排序。

2.8.1 算法步骤

  1. 找到列表中的最大数,确定最大数的位数。
  2. 从最低位开始,对列表进行排序。
  3. 重复步骤2,直到最高位。

2.8.2 Java实现

public class RadixSort {
    public static void radixSort(int[] arr) {
        int max = Arrays.stream(arr).max().getAsInt();
        for (int exp = 1; max / exp > 0; exp *= 10) {
            countingSortByDigit(arr, exp);
        }
    }

    public static void countingSortByDigit(int[] arr, int exp) {
        int n = arr.length;
        int[] output = new int[n];
        int[] count = new int[10];

        // 统计每个数字的出现次数
        for (int i = 0; i < n; i++) {
            count[(arr[i] / exp) % 10]++;
        }

        // 计算每个数字的最终位置
        for (int i = 1; i < 10; i++) {
            count[i] += count[i - 1];
        }

        // 将元素放回原列表
        for (int i = n - 1; i >= 0; i--) {
            output[count[(arr[i] / exp) % 10] - 1] = arr[i];
            count[(arr[i] / exp) % 10]--;
        }

        // 将排序结果复制回原数组
        System.arraycopy(output, 0, arr, 0, n);
    }

    public static void main(String[] args) {
        int[] arr = {170, 45, 75, 90, 802, 24, 2, 66};
        radixSort(arr);
        System.out.println("排序后的数组:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

2.8.3 时间复杂度

2.9 桶排序(Bucket Sort)

桶排序是一种非比较排序算法。它将列表分成若干个桶,每个桶内的元素进行排序,然后将所有桶的元素合并成一个有序列表。

2.9.1 算法步骤

  1. 将列表分成若干个桶。
  2. 对每个桶内的元素进行排序。
  3. 将所有桶的元素合并成一个有序列表。

2.9.2 Java实现

”`java import java.util.ArrayList; import java.util.Collections;

public class BucketSort { public static void bucketSort(int[] arr) { int n = arr.length; int max = Arrays.stream(arr).max().getAsInt(); int min = Arrays.stream(arr).min().getAsInt(); int bucketSize = (max - min) / n + 1;

    ArrayList<ArrayList<Integer>> buckets = new ArrayList<>(n);
    for (int i = 0; i < n; i++) {
        buckets.add(new ArrayList<>());
    }

    // 将元素分配到各个桶中
    for (int i = 0; i < n; i++) {
        int bucketIndex = (arr[i] - min) / bucketSize;
        buckets.get(bucketIndex).add(arr[i]);
    }

    // 对每个桶内的元素进行排序
    for (ArrayList<Integer> bucket : buckets) {
        Collections.sort(bucket);
    }

    // 将所有桶的元素合并成一个有序列表
    int index = 0;
    for (ArrayList<Integer> bucket : buckets) {
        for (int num : bucket) {
            arr[index++] = num;
        }
    }
}

public static
推荐阅读:
  1. java排序算法之如何实现希尔排序
  2. Java排序算法之冒泡排序

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:pytorch模型怎么转onnx模型

下一篇:如何用python代码绘制三维图

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》