Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Scanner;
- /**
- * Created by MOHIT on 10-09-2017.
- */
- // Program to implement quick sort in java
- public class quick_sort{
- public static void main(String arg[]){
- // accepting string as comma seperated inputs
- String input_string;
- ArrayList<Integer> myList1 = new ArrayList<Integer>();
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter the Array to be Sorted : ");
- input_string = sc.next();
- String[] temp = input_string.split(",");
- // adding those integers to array list
- for (String t:temp) {
- myList1.add(Integer.parseInt(t));
- }
- // print the list
- System.out.println("The list before sorting is : ")
- for (int temp2:myList1) {
- System.out.print(temp2 + "\t");
- }
- // calling the quick sort function with first position as 0 and last position as list size -1
- myList1 = Quick_Sort(myList1, 0, myList1.size()-1);
- // printing the sorted list
- System.out.println("\nThe Sorted List is : ");
- // displaying the sorted list
- for (int temp2:myList1) {
- System.out.print(temp2 + "\t");
- }
- }
- // recursive function to implement quick sort
- static ArrayList<Integer> Quick_Sort(ArrayList<Integer> data, int first, int last)
- {
- int pivot, left_mark, right_mark;
- // checking if the list has more than one number
- if(first < last)
- {
- // initialise variables
- pivot = first;
- left_mark = first;
- right_mark = last;
- // loop while left marker is less than right marker
- while(left_mark < right_mark)
- {
- // while the data at the left mark is less than pivot keep incrementing the left_mark
- while(data.get(left_mark) <= data.get(pivot) && left_mark < right_mark)
- left_mark++;
- // while the data at the right mark is greater than pivot keep decrementing the right_mark
- while(data.get(right_mark) >= data.get(pivot) && left_mark <= right_mark)
- right_mark--;
- // swap the elements if right mark is greater than left mark
- if(right_mark > left_mark)
- {
- Collections.swap(data, left_mark, right_mark);
- }
- // finally swap the pivot and the right mark element
- Collections.swap(data, pivot, right_mark);
- }
- // make recursive calls to the function
- Quick_Sort(data, first, right_mark-1);
- Quick_Sort(data, right_mark+1, last);
- }
- // returning the sorted list
- return data;
- }
- }
Add Comment
Please, Sign In to add comment