2025-01-15 1.时间复杂度 2.冒泡排序

This commit is contained in:
liangjinglin 2025-01-15 20:08:30 +08:00
parent 48746fa165
commit e50079795d
2 changed files with 107 additions and 0 deletions

View File

@ -0,0 +1,67 @@
package SortAlgori;
import java.util.Scanner;
public class BubbleSort {
private int[] arr;
public BubbleSort(String str){
String[] splitArrs = str.split(";");
arr = new int[splitArrs.length];
for (int i = 0; i < splitArrs.length; i++) {
arr[i] = Integer.parseInt(splitArrs[i]);
}
}
public BubbleSort(int[] arr){
this.arr = arr;
}
/**
* 可以进行一个优化如果在某一趟排序中没发生过交换就说明已经排好序了
*/
public void sort(){
boolean flag = false;
for (int i=0 ; i<arr.length-1; i++){
for(int j=0; j<arr.length-i-1; j++){
if(arr[j]>arr[j+1]){
flag = true;
int temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
if(!flag){
break;
}else {
flag = false;
}
}
}
public void show(){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = new int[10000];
System.out.println("排序前的序列:");
for(int i=0; i<10000; i++){
arr[i] = (int)(Math.random()*1000000);
System.out.print(arr[i] + " ");
}
System.out.println();
BubbleSort bubbleSort = new BubbleSort(arr);
long startTime = System.currentTimeMillis();
bubbleSort.sort();
long endTime = System.currentTimeMillis();
System.out.println("排序后的序列:");
bubbleSort.show();
System.out.println("排序所花费的时间:" + (endTime - startTime) + "ms");
}
}

View File

@ -0,0 +1,40 @@
package SortAlgori;
public class TimeComplex {
private int constant(int n){
return (1+n)*n/2;
}
private int log2n(int n){
int i = 1;
while (i < n){
i = i * 2;
}
return i;
}
private void linear(int n){
for(int i = 0; i<n; i++){
System.out.printf("i = %d\n",i);
}
}
private void nlog2n(int n){
for(int i = 0; i<n; i++){
int j = 1;
while (j < n){
j = j * 2;
}
System.out.printf("i = %d\n",i);
}
}
private void square(int n){
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
System.out.printf("i = %d,j = %d\n",i,j);
}
}
}
}