Article directory
Time and Space Complexity Analysis – Bubble Sort Algorithm
roughly
What is Bubble Sort Algorithm?
The bubble sorting algorithm is to perform n rounds of large exchanges, and each round compares the size of two adjacent numbers and performs exchanges.
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-WFG1VuGd-1661504862731) (C:\Users\dongxu.kwb\Downloads\Unnamed file (1)]. png)
code part
/**
* @author `dongxu.kwb`
* @date `2022/8/26`
*/
public class PaoSort {
public static void main(String[] args) {
int[] arr = {79,3213,3,5,45,65};
paoSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void paoSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length-1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
}
}
Time complexity analysis & space complexity analysis of it
Let me talk about the time complexity first:
for
It is these two loops that affect its time complexity
or (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length-1; j++) {
}
}
The first for loop executes n
times, and it nests a n-1
loop inside it, n(n-1)
, so the time complexity is O( n 2 n^{2}n2)
Let's talk about space complexity
Space complexity Because the variable created is temp
so the space complexity is O(1).