使用排序和随机方法创建动态数组,这两种方法都无法正常工作



对于Java类,我们必须创建一个动态数组。不能使用数组列表。

这是我定义类的地方

public class DynamicArray {
private int array[];
private int size;

下面是调用的构造函数:

/**
* DynamicArray     copies the array
* @param obj 
*/
public DynamicArray(DynamicArray obj) {
array = obj.toArray();
size = obj.getSize();
}

在 main 方法下,这里是我创建新的数组对象并尝试排序和随机播放的地方(以及其他一些方法,但这些方法有效(:

/**
* Calling the copy constructor, which calls the toArray method
* Calling get method
* Calling indexOfMethod
* Calling findMax
* Calling findMin
* Calling shuffle
*/
DynamicArray array3 = new DynamicArray(array2);
array3.push(100);
array3.push(150);
array3.push(100);
System.out.println(array3);
array3.pop();
System.out.println(array3);
System.out.println("This number is at index 5: " + array3.get(5));
System.out.println("The number 100 first appears at index: " + array3.indexOf(100));
System.out.println("The highest number is: " + array3.findMax());
System.out.println("The lowest number is: " + array3.findMin());
System.out.println(array3);
array3.shuffle();
System.out.println(array3);
array3.sort(array3.toArray());

toArray 方法是这样的:

/**
* toArray      accessor returns the array
* @return 
*/
public int[] toArray() {
int arrayCopy[] = new int[array.length];
for (int i = 0; i < array.length; i++) {
arrayCopy[i] = array[i];
}
return arrayCopy;
}

排序和随机排序方法是这样的:

/**
* isEmpty      returns size = 0 is array is empty
* @return 0 if empty
*/
public boolean isEmpty() {
return size == 0;
}
/**
* sort     sorts the numbers in the array
*/
public void sort(int [] array) {
int lastPos;
int index;
int newNum;
for (lastPos = array.length - 1; lastPos >= 0; lastPos--) {
for (index = 0; index <= lastPos - 1; index++) {
if (array[index] > array[index + 1]) {
newNum = array[index];
array[index] = array[index + 1];
array[index + 1] = newNum;
}
}
}
}
/**
* shuffle      shuffles the array
*/
public void shuffle() {
Random r = new Random();
for (int i = array.length - 1; i > 0; i--) {
int index = r.nextInt(i);
int tmp = array[i];
array[i] = array[index];
array[index] = tmp;
}
}

排序的输出中有 0:

0, 0, 0, 10, 0,0, 150, 0, 2,

洗牌不会改变任何东西。

这些是在辅导实验室的帮助下创建的,我将它们与在线推荐进行了比较。

这是怎么回事?

更新:

下面是数组 2:

/**
* Calling constructor with parameter
* also calling push to add items to the array
*/
DynamicArray array2 = new DynamicArray(5);
array2.push(4);
array2.push(10);
array2.push(15);
array2.push(18);
array2.push(2);
array2.push(25);
System.out.println("Size is: " + array2.getSize());
array2.push(20);
System.out.println("Size is: " + array2.getSize());
System.out.println(array2);

这是 getSize((

/**
* getSize     gets size of the array
* @return size
*/
public int getSize() {
return size;
}

您能否提供有关如何实例化array2的信息?它是算法的起点。

getSize((实现也很有用。

现在,您可以在此处检查排序算法: https://www.geeksforgeeks.org/sorting-algorithms/例如,气泡排序非常容易理解和实现。

对于随机播放实现,您可以检查: http://www.vogella.com/tutorials/JavaAlgorithmsShuffle/article.html

最新更新