DEV Community

ItzEve
ItzEve

Posted on

1

Small issue.

I am having a small issue...

I have a class Movie with a static array Movie[] movies. I implement the Comparable and i overload the method compareTo. If the likes of a movie are same with the likes of another movie then i compare them with alphabetical order. I have to create a quicksort implementation to sort an array of movies. But in line return this.compareTo(m); i got a stack overflow Error. How i am supposed to fix this ?

` public int compareTo(Movie m) {
if (this.likes == m.likes) {
//DefaultComparator cmp = new DefaultComparator();
return this.compareTo(m);
} else if (this.likes > m.likes) {
return 1;
} else {
return -1;
}

    }

    public static Movie[] sort(Movie[] m) {
        if (m == null || m.length == 0) {
            return null;
        } else {
            movies = m;
            quicksort(0, movies.length - 1); // sort the entire array
            return movies;
        }
    }

    public static void quicksort(int left, int right) {
        int i = left;
        int j = right;
        Movie pivot = movies[left + (right - left) / 2];
        while (i <= j) {
            while (movies[i].compareTo(pivot) == -1) {
                i++;
            }
            while (movies[j].compareTo(pivot) == 1) {
                j--;
            }
            if (i <= j) {
                exch(i, j);
                i++;
                j--;
            }

        }
        if (left < j) {
            quicksort(left, j);
        }
        if (i < right) {
            quicksort(i, right);
        }
    }

    public static void exch(int i, int j) {
        Movie temp = movies[i];
        movies[i] = movies[j];
        movies[j] = temp;
    }`
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)