我编写了以下程序(冒泡,选择,插入),我想检查它们的时间和空间复杂度。任何人都可以指导我是否正确,因为互联网/书籍上的大多数程序都是使用Arrays而不是ArrayList。
public class BubbleSort {
List<Integer> unsortedList;
private BubbleSort() {
unsortedList = new ArrayList<Integer>();
unsortedList.add(0, 6);
unsortedList.add(1, 3);
unsortedList.add(2, 7);
unsortedList.add(3, 4);
unsortedList.add(4, 2);
unsortedList.add(5, 3);
unsortedList.add(6, 8);
}
private void sortData() {
ArrayList<Integer> tempList = (ArrayList<Integer>) this.unsortedList;
int size = unsortedList.size();
int counter = size;
do {
for (int i = 0; i < size-1; i++) {
if (unsortedList.get(i) > unsortedList.get(i + 1)) {
Integer temp1= unsortedList.get(i + 1);
Integer temp2= unsortedList.get(i);
unsortedList.set(i,temp1);
unsortedList.set(i+1,temp2);
}
}
size = size - 1;
} while (size != 1);
}
public static void main(String arg[]) {
BubbleSort obj = new BubbleSort();
obj.sortData();
for(Integer i:obj.unsortedList){
System.out.println(i);
}
}}
public class SelectionSort {
List<Integer> unsortedList;
private SelectionSort() {
unsortedList = new ArrayList<Integer>();
unsortedList.add(0, 16);
unsortedList.add(1, 3);
unsortedList.add(2, 7);
unsortedList.add(3, 4);
unsortedList.add(4, 12);
unsortedList.add(5, 3);
unsortedList.add(6, 8);
unsortedList.add(7, 18);
unsortedList.add(8, 81);
unsortedList.add(9, 2);
}
public void sortData() {
int totalPass = unsortedList.size();
int listLength = totalPass;
for (int i = 0; i <= totalPass - 1; i++) {
int pointerSmallPosition=i;
for (int j = i; j < listLength-1; j++) {
if (unsortedList.get(pointerSmallPosition) > unsortedList.get(j + 1)) {
pointerSmallPosition=j + 1;
}
}
int temp1= unsortedList.get(i);
int temp2= unsortedList.get(pointerSmallPosition);
unsortedList.set(i,temp2);
unsortedList.set(pointerSmallPosition,temp1);
}
}
public static void main(String arg[]) {
SelectionSort obj = new SelectionSort();
obj.sortData();
for (Integer i : obj.unsortedList) {
System.out.println(i);
}
}}
public class InsertionSort {
List<Integer> unsortedList;
public InsertionSort(){
unsortedList = new ArrayList<Integer>();
unsortedList.add(0, 6);
unsortedList.add(1, 3);
unsortedList.add(2, 7);
unsortedList.add(3, 4);
unsortedList.add(4, 2);
unsortedList.add(5, 3);
unsortedList.add(6, 8);
}
public static void main(String arg[]){
InsertionSort obj=new InsertionSort();
obj.sortData();
for(Integer i:obj.unsortedList){
System.out.println(i);
}
}
private void sortData() {
int size = unsortedList.size();
int sortedSize=0;
for(int i=1;i<size-1;i++){
int j=i;
do{
if(unsortedList.get(j)<unsortedList.get(j-1)){
int small=unsortedList.get(j);
int large=unsortedList.get(j-1);
unsortedList.set(j-1, small);
unsortedList.set(j, large);
}
j--;
}while(j>sortedSize);
}}}
答案 0 :(得分:0)
要分析复杂性,您可以使用Big O notation。我把你联系到一张桌子,可以帮助你理解它的理论。使用ArrayList在Big O中并不重要;你只需要关心主要过程&#34;你的算法。在你的例子中是循环定义N或N ^ x ...
如果您想查看算法用于完成的时间,可以使用Antonio said的帖子。