[英]How to find exact Time complexity and Space Complexity for below new Quick sort algorithm
我创建了一种新的排序算法,该算法的基本概念是从给定列表中找到最小和最大元素,然后将它们与左角和右角元素交换,这将一直重复到我们到达中间元素为止。
与快速排序和合并排序相比,此算法执行的时间要短得多。 我想确定这种算法是否比快速排序更好。
我的算法代码
public class VeryQuickVersion1
{
public static void main(String args[])
{
long current = System.nanoTime();
int[] first = { 8 ,1 ,3 ,2, 6, 5, 7, 4, 12 ,9, 11 ,10 ,14 ,13, 15};
for (int x=0,y=first.length - 1;x<y;x++,y--)
{
int low = 0;
int high = 0;
int li = 0;
int hi = 0;
for (int i = x; i <= y; i++)
{
if (i == x)
{
low = first[i];
high = first[i];
}
if (low > first[i])
{
low = first[i];
li = i;
}
if (high < first[i])
{
high = first[i];
hi = i;
}
}
first[li]=first[x];
first[hi]=first[y];
first[x]=low;
first[y]=high;
}
/* for(int i:first){
System.out.println(i);
}*/
System.out.println(System.nanoTime() - current);
}
}
该算法花费的时间是:10148,而快速排序算法花费的相同列表的时间是:17498
上述算法的时间复杂度似乎是O(n^2)
。
如您所见,有2个嵌套的for
循环。 外部一个从x = 0, y = n
到x < y
,并且在每个步骤中它都会减少x++
和y--
。 而另一个内部循环从x
到y
。
这可以看作是级数n + (n-2) + (n-4) + .... + 0
。 显然可以得出时间复杂度O(n^2)
时间复杂度不是按照您的方式计算的。 您应该检查当输入大小增加时,此程序花费的时间将如何增加 。 并使用不同类型的输入 (如升序,随机等)进行测试。
收集了非常大的输入和不同类型的输入的数据后,您将看到O(nlogn)
时间复杂度的算法与O(n^2)
时间复杂度的算法之间的区别。
注意:您可以在此网站上看到花费时间增加的真正区别。 注意输入的长度增加到50000
后所花费的时间如何增加。
您不会在数据量如此小的任何算法上设置基准。 数组的大小为10,这确实很小。
创建大小为〜10 ^ 5或10 ^ 6的数组,然后检查性能。
另外,仅通过查看代码,我就能知道该算法比快速排序更差。 在渐近复杂度中,快速排序是O(n log n),而这个显然是O(n ^ 2)。
我使用Arrays.sort使用快速排序对数组进行排序。
结果如下:
数组大小1000
For Quick Sort algorithm:
1817634
For my algorithm:
8105038
数组大小100000
For Quick Sort algorithm:
21210010
For my algorithm:
7117304154
您可以清楚地看到区别。
我的代码仅供参考:(对于我的算法,我只是复制了您的代码)
import java.util.*;
public class Quick{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] first = new int[n];
for(int i = 0; i < n; i++){
first[i] = in.nextInt();
}
int second[] = first.clone();
long current = System.nanoTime();
Arrays.sort(second);
System.out.println("For Quick Sort algorithm:\n" + (System.nanoTime() - current) + "\n");
current = System.nanoTime();
for (int x=0,y=first.length - 1;x<y;x++,y--) {
int low = 0;
int high = 0;
int li = 0;
int hi = 0;
for (int i = x; i <= y; i++) {
if (i == x) {
low = first[i];
high = first[i];
}
if (low > first[i]) {
low = first[i];
li = i;
}
if (high < first[i]) {
high = first[i];
hi = i;
}
}
first[li]=first[x];
first[hi]=first[y];
first[x]=low;
first[y]=high;
}
/* for(int i:first){
System.out.println(i);
}*/
System.out.println("For my algorithm:\n" + (System.nanoTime() - current));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.