DEV Community

Cover image for Day 30: Quick Sort
Matt Ryan
Matt Ryan

Posted on

2 2

Day 30: Quick Sort

Alt Text

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;



public class Day30 {

    static int partition(int[] array, int low, int high) {

        int j, temp, i = low + 1;

        Random random = new Random();

        int x = random.nextInt(high - low) + low;

        temp = array[low];

        array[low] = array[x];

        array[x] = temp;

        for (j = low + 1; j <= high; j++) {

            if (array[j] <= array[low] && j != i) {

                temp = array[j];

                array[j] = array[i];

                array[i++] = temp;

            } else if (array[j] <= array[low]) {

                i++;

            }

        }

        temp = array[i - 1];

        array[i - 1] = array[low];

        array[low] = temp;

        return i - 1;

    }

    static void Day30(int[] array,int low,int high){

        if(low<high){

            int mid = partition(array,low,high);

            Day30(array,low,mid-1);

            Day30(array,mid+1,high);

        }

    }

    public static void main(String[] args) {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int size;

        System.out.println("Enter the size of the array");

        try {

            size = Integer.parseInt(br.readLine());

        } catch (Exception e) {

            System.out.println("Invalid Input");

            return;

        }

        int[] array = new int[size];

        System.out.println("Enter array elements");

        int i;

        for (i = 0; i < array.length; i++) {

            try {

                array[i] = Integer.parseInt(br.readLine());

            } catch (Exception e) {

                System.out.println("Error");

            }

        }

        System.out.println("The initial array is");
        System.out.println(Arrays.toString(array));
        Day30(array,0,array.length-1);
        System.out.println("The sorted array is");
        System.out.println(Arrays.toString(array));

    }

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.