Skip to content

Commit c2c6c8b

Browse files
committed
Implement quicksort
1 parent 10c9e6a commit c2c6c8b

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Quicksort.java

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import java.util.Scanner;
2+
3+
public class Quicksort{
4+
5+
public static void main(String[] args){
6+
Scanner input = new Scanner(System.in);
7+
int[] array;
8+
int size = 0;
9+
10+
//Prompt user to create array and its elements
11+
System.out.print("Enter the size of the array: ");
12+
size = input.nextInt();
13+
array = new int[size];
14+
for (int i = 0; i < size; i++){
15+
System.out.print("For index " + i + ", give an integer input: ");
16+
array[i] = input.nextInt();
17+
}
18+
19+
//Output inputted array
20+
System.out.println("The array is: ");
21+
printarray(array);
22+
System.out.println();
23+
24+
//Run quicksort, and output sorted array
25+
quicksort(array, 0, array.length - 1);
26+
System.out.println("The sorted array is: ");
27+
printarray(array);
28+
System.out.println();
29+
}
30+
31+
//Quicksort Method
32+
public static void quicksort(int[] ar, int start, int end){
33+
int[] array;
34+
35+
int i = start, j = end;
36+
if (end-start >= 1){
37+
int pivot = ar[end];
38+
while (i< j){
39+
while (ar[i]<pivot && i<end){
40+
i++;
41+
}
42+
while (ar[j]>=pivot && j>start){
43+
j--;
44+
}
45+
if (i<j){
46+
swap(ar, i, j);
47+
}
48+
} swap(ar, end, i);
49+
50+
quicksort(ar, start, i-1);
51+
quicksort(ar, i+1, end);
52+
} else{
53+
return;
54+
}
55+
}
56+
57+
//Helper methods
58+
public static void swap(int[] ar, int index1, int index2){
59+
60+
int temp = ar[index1];
61+
ar[index1] = ar[index2];
62+
ar[index2] = temp;
63+
}
64+
65+
public static void printarray(int[] array){
66+
67+
for (int data : array){
68+
System.out.print(data + " ");
69+
}
70+
}
71+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy