Write a DSA Program Quick Sort using Java - Technology369kk

Program:

import java.util.*;

class QuickSort{
//class QuickSort function.
public static void sort(int[] arr) {
quickSort(arr, 0, arr.length - 1);
}

public static void quickSort(int[] arr, int low, int high) {
int l = low, h = high;
int pivot = arr[(low + high) / 2];

while (l <= h) {
while (arr[l] < pivot) l++;
while (arr[h] > pivot) h--;
if (l <= h) {
int temp = arr[l];
arr[l] = arr[h];
arr[h] = temp;
l++;
h--;
}
}

if (low < h) quickSort(arr, low, h);
if (l < high) quickSort(arr, l, high);
}


// Main methods
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.err.println("Quick Sort Test\n");
int n, i;

// Accepts Number of elements
System.out.println("Enter number of integer elements");
n = sc.nextInt();

// Create array of n elements
int arr[] = new int[n];

// Accepts elements

System.out.println("\n Enter "+n+" interger elements");

for(i=0; i<n; i++){
arr[i] =sc.nextInt();
}
// call methods sort
sort(arr);

// Print sorted Array
System.out.println("\n Elements after sorting");

for(i=0; i<n; i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
}



Answer:


QuickSort
Quick Sort Test

Enter number of integer elements

3

Enter 3 interger elements
5
8
9

Elements after sorting
5 8 9 
 

Post a Comment

0 Comments