我需要创建一个随机的int数组,并按照我自己的类进行排序。这是我制作数组的地方:
public class MyProgram9{
public static void main(String[] args){
int[] list = new int[10];
for (int i=0; i<10; i++){
int n = (int)(Math.random()*9 + 1);
list[i] = n;
System.out.println(list[i] + " ");
}
list.QuickSort();
}
}
然后我尝试使用另一个类对其进行排序(QuickSort类)。我的问题是如何从同一个文件夹中实现这个类,以便我可以使用它。这是quickSort类:
public class QuickSort{
public static void quickSort(int[] list){
quickSort(list, 0, list.length - 1);
}
private static void quickSort(int[] list, int first, int last) {
if (last > first) {
int pivotIndex = partition(list, first, last);
quickSort(list, first, pivotIndex - 1);
quickSort(list, pivotIndex + 1, last);
}
}
/** Partition the array list[first..last] */
private static int partition(int[] list, int first, int last) {
int pivot = list[first]; // Choose the first element as the pivot
int low = first + 1; // Index for forward search
int high = last; // Index for backward search
while (high > low) {
// Search forward from left
while (low <= high && list[low] <= pivot)
low++;
// Search backward from right
while (low <= high && list[high] > pivot)
high--;
// Swap two elements in the list
if (high > low) {
int temp = list[high];
list[high] = list[low];
list[low] = temp;
}
}
while (high > first && list[high] >= pivot)
high--;
// Swap pivot with list[high]
if (pivot > list[high]) {
list[first] = list[high];
list[high] = pivot;
return high;
}
else {
return first;
}
}
}
对所有信息感到抱歉。
答案 0 :(得分:3)
如果您的意思是如何连接这两个类,那么您的代码就错了。您必须在阵列上调用静态快速排序方法。像:
public class MyProgram9{
public static void main(String[] args){
int[] list = new int[10];
for (int i=0; i<10; i++){
int n = (int)(Math.random()*9 + 1);
list[i] = n;
System.out.println(list[i] + " ");
}
QuickSort.quicksort(list);
}
}
答案 1 :(得分:0)
您需要用
替换main方法的最后一行QuickSort.quickSort(list);
答案 2 :(得分:0)
import java.util.Random;
public class Array {
public static void main(String[] args) {
Random random= new Random();
int numbers[]= new int[10];
for (int i = 0; i < 10; i++)
{
int number= random.nextInt(100);
System.out.println(number);
numbers[i]=number;
}
for (int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}
}
}