0

I am trying to find the middle index in an array (of type long) The problem im solving specifically asks for a long to return, so I cant change the signature I want to find the pivot point, in my quicksort code, but I get an error "possible lossy conversion from long to int" I understand that I may lose some information when dividing, but I want to bypass it here is the code containing the error:

public static long partition(long[] array, long left, long right){
    long i = left, j = right;
    long tmp;
    long pivot = array[(left + right) / 2];  // <-----ERROR HERE  <------

    while(i <= j) {
        while(array[i] < pivot){
        i--;
       }
       while(array[j] > pivot) {
           j--;
       }
       if(i <= j) {
           tmp =array[i];
           array[i] = array[j];
           array[j] = tmp;
           i++;
           j--;
       }
       }
    return i;
}
nugh
  • 135
  • 2
  • 7

3 Answers3

3

From JLS Sec 10.4:

Arrays must be indexed by int values

Using long for the left and right parameters (and i and j) is meaningless (because an array can't have that many elements), and will result in a compile-time error. Change them to int.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

use "array[index]", this "index" must be int. so

long pivot = array[(int)((left + right) / 2)];
Heng Lin
  • 96
  • 6
-1

I tried typecasting the long to int like.. long pivot = array[(int) ((left + right) / 2)]; It works for me, can you please elaborate in which scenario you are getting the error "possible lossy conversion from long to int".

Manish
  • 31
  • 3