21xrx.com
2024-11-08 23:14:13 Friday
登录
文章检索 我的文章 写文章
Java Sorting Algorithms: Time Complexity Analysis and Code Examples
2023-06-12 05:14:30 深夜i     --     --
Java

Java Sorting Algorithms: Time Complexity Analysis and Code Examples

Java provides numerous sorting algorithms that can be used to arrange data based on different criteria. However, each sorting algorithm has its own efficiency and performance in terms of time complexity. This article will explore the time complexity of various sorting algorithms in Java and provide corresponding code examples.

1. Bubble Sort

Bubble Sort is one of the simplest sorting algorithms that traverses an array multiple times and compares adjacent elements to arrange them in order. Its time complexity is O(n^2), making it inefficient for large datasets.

Code Example:

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]) {

      int temp = arr[j];

      arr[j] = arr[j+1];

      arr[j+1] = temp;

     }

}

2. Selection Sort

Selection Sort traverses an array multiple times and selects the smallest element each time to place it at the beginning. Its time complexity is also O(n^2), making it inefficient for large datasets.

Code Example:

public static void selectionSort(int[] arr) {

  int n = arr.length;

  for (int i = 0; i < n-1; i++) {

   int min_idx = i;

   for (int j = i+1; j < n; j++)

     if (arr[j] < arr[min_idx])

      min_idx = j;

   int temp = arr[min_idx];

   arr[min_idx] = arr[i];

   arr[i] = temp;

  }

}

3. Insertion Sort

Insertion Sort traverses an array multiple times and inserts each element in its correct position. Its time complexity is O(n^2), but it performs better than Bubble Sort and Selection Sort for smaller datasets.

Code Example:

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 = j - 1;

   }

   arr[j + 1] = key;

  }

}

Sorting Algorithms, Time Complexity, Bubble Sort, Selection Sort, Insertion Sort.

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复