import java.util.ArrayList;
import java.util.Random;
public class Sorting
{
public static int numOfComps = 0,
numOfSwaps = 0;
public static void main(String[] args)
{
System.out.println("\nOriginal order:");
int size = 5;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++)
{
list.add(i);
}
Random rand = new Random();
while(list.size() > 0)
{
int index = rand.nextInt(list.size());
System.out.print(list.remove(index) + " ");
}
System.out.println();
int[] test = convertIntegers(list);
int[] a = new int[5];
// Selection Sort
System.out.println("\n\nSelection Sort");
// Display copy of random generated number original order
System.out.println("\nOriginal order:");
System.arraycopy(test, 0, a, 0, test.length);
System.out.println(a + " ");
// Selection Sort method
selectionSort(a);
System.out.println("\nSorted order: ");
for(int element : a)
System.out.print(element + " ");
}
public static int[] convertIntegers(ArrayList<Integer> integers)
{
int[] num = new int[integers.size()];
for (int i=0; i < num.length; i++)
{
num[i] = integers.get(i).intValue();
}
return num;
}
public static void selectionSort(int[] array)
{
int startScan; // Starting position of the scan
int index; // To hold a subscript value
int minIndex; // Element with smallest value in the scan
int minValue; // The smallest value found in the scan
// The outer loop iterates once for each element in the
// array. The startScan variable marks the position where
// the scan should begin.
for (startScan = 0; startScan < (array.length-1); startScan++)
{
// Assume the first element in the scannable area
// is the smallest value.
minIndex = startScan;
minValue = array[startScan];
// Scan the array, starting at the 2nd element in
// the scannable area. We are looking for the smallest
// value in the scannable area.
for(index = startScan + 1; index < array.length; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
// Counts the number of values comparisons
numOfComps ++;
}
// Counts the number of values swaps
if(minIndex != startScan)
{
numOfSwaps ++;
}
// Swap the element with the smallest value
// with the first element in the scannable area.
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
System.out.println("\nNumber of comps = " + numOfComps);
System.out.println("Number of swaps = " + numOfSwaps);
}
}
如何编写代码以将随机生成的数字复制到选择排序方法,以便随机生成的数字可以在显示的标题“选择排序”下显示为精确副本,以及显示比较和交换的数量,和排序的顺序?我提供的代码无法正常工作。谢谢你的帮助。
答案 0 :(得分:0)
for(int i = 0; i< arr.length; i++){
//generate random number here and assign to arr[i]
}
enter code here
现在添加另一个for循环来显示数组中的所有内容,然后如果你想查看它是否有效,则使用另一个循环。