[英]Use an arraylist instead of array
The code is designed for the array, I want to use ArrayList in this code, the code ArrayList is added below the origin array.代码是为数组设计的,我想在这段代码中使用 ArrayList,代码 ArrayList 是在原始数组下面添加的。 But the code seems like can't read the elements in the ArrayList.但是代码似乎无法读取 ArrayList 中的元素。 How can I make it possible?我怎样才能使它成为可能?
It only returns 0 now, and I guess that's because it can't read the elements in the ArrayList?它现在只返回 0,我猜这是因为它无法读取 ArrayList 中的元素?
Here is my code.这是我的代码。 Why did this happen and how can I fix it?为什么会发生这种情况,我该如何解决?
import java.util.*;
class RandomisedQuickSort
{
public static int N = 5;
public static int[] arr = new int[N];
void random(int low,int high)
{
Random rand= new Random();
int pivot = rand.nextInt(high-low) + low;
int temp1=arr[pivot];
arr[pivot]=arr[high];
arr[high]=temp1;
}
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1);
for (int j = low; j < high; j++)
{
if (arr[j] <= pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
void sort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String args[])
{
//int arr[] = {10, 7, 8, 9, 1, 5};
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
list.add(i);
}
Collections.shuffle(list);
int n = arr.length;
RandomisedQuickSort ob = new RandomisedQuickSort();
ob.sort(arr, 0, n-1);
System.out.println("sorted array");
printArray(arr);
}
}
You are using Integer[]
but sort()
and printArray()
expect int[]
您正在使用Integer[]
但sort()
和printArray()
期望int[]
void sort(int arr[], int low, int high) {...}
static void printArray(int arr[]) {..}
You can convert Arraylist into int[]
this way and use您可以通过这种方式将 Arraylist 转换为int[]
并使用
int[] arr = list.stream().mapToInt(i->i).toArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.