gpt4 book ai didi

java - 确定程序是否快速、内存效率高且时间复杂度不高

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:46 24 4
gpt4 key购买 nike

有人可以帮助我如何确定我的程序是否内存高效、速度快且时间复杂度低?对于我的一个程序,我实现了合并排序,然后到处调用一些方法,但由于它有大约 100 行代码,我怀疑它是否具有内存效率。谢谢大家

import java.util.*;

public class Question6 {

static void mergeSort(Integer arr1[], int o, int k, int x) {

int num1 = k - o + 1;
int num2 = x - k;

int temp1[] = new int[num1]; //creation of two temporary arrays to store in
int temp2[] = new int[num2];


for (int i = 0; i < num1; ++i) //for loops to copy the data to the temporary arrays
temp1[i] = arr1[o + i];

for (int j = 0; j < num2; ++j)
temp2[j] = arr1[k + 1 + j];


int i = 0, j = 0; //starting position of temporary arrays


int s = o; //starting position of the merged two temporary arrays
while (i < num1 && j < num2) {

if (temp1[i] <= temp2[j]) {
arr1[s] = temp1[i];
i++;
} else {
arr1[s] = temp2[j];
j++;
}
s++;
}

//code to copy elements from temp1
while (i < num1) {
arr1[s] = temp1[i];
i++;
s++;
}

//code to copy elements from temp2
while (j < num2) {
arr1[s] = temp2[j];
j++;
s++;
}
}


void forSorting(Integer arr2[], Integer t, Integer x) //main method that carries out merge sort
{
if (t < x) {
// Find the middle point
Integer a = (t + x) / 2;

// Sort first and second halves
forSorting(arr2, t, a);
forSorting(arr2, a + 1, x);

// Merge the sorted halves
mergeSort(arr2, t, a, x);
}
}

public static void main(String[] args) {
Question6 qs = new Question6();
Scanner sc = new Scanner(System.in);
Integer[] duplicate = new Integer[10];

System.out.println("Please input the numbers to be checked for repetition.");

for (int x = 0; x < 10; x++) {
duplicate[x] = sc.nextInt(); //filling array
}

int length = duplicate.length;
qs.forSorting(duplicate, 0, length - 1); //calling method forSorting

System.out.println(Arrays.toString(duplicate)); //displays the array which user fills

List<Integer> list = Arrays.asList(duplicate); //makes the array duplicate available as a list

Set<Integer> set = new LinkedHashSet<Integer>(list);

for ( Integer element : set) {

if(Collections.frequency(list, element) > 1) {

System.out.println(" Duplicate: " + element);
}
}
}
}

最佳答案

您可以使用探查器。对于 Java - JProfiler、VisualVM 等。您可以在那里检查您想要的所有内容 - 您的算法需要多少内存、时间复杂度以及更多内容。

关于java - 确定程序是否快速、内存效率高且时间复杂度不高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49602891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com