2011-11-15 63 views
0

我需要創建一個隨機數組的int並讓它按照我自己的類進行排序。這裏是我的陣列:創建一個int類型的隨機數組。 Java

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

更換你的主要方法的最後一行是什麼您從同一個文件夾意思? – Tudor

+0

'list.QuickSort()'不是有效的Java。我建議你包括一個編譯代碼示例.. – mre

+1

聽起來像作業... – Laf

回答

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); 
} 
} 
0

您需要

QuickSort.quickSort(list); 
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]); 
     } 
    } 

}