-
Notifications
You must be signed in to change notification settings - Fork 694
/
Copy pathSolution.java
93 lines (76 loc) · 2.25 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//Problem: https://www.hackerrank.com/challenges/quicksort4
//Java 8
/*
Initial Thoughts:
We can just add a counter in our swap function of each sorting algorithm and compare them
Time Complexity: O(n^2) //We are not randomizing our pivot selection so worst case is n^2
Space Complexity: O(log n) //We recursively build log n frames on the stack
*/
import java.io.*;
import java.util.*;
public class Solution {
static int Qswaps = 0;
static int Iswaps = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int ar[] = new int[n];
for(int i = 0; i < n; i++)
{
ar[i] = input.nextInt();
}
//Run insertion sort on its own copy
int[] copy = ar.clone();
insertionSort(copy);
quicksort(ar,0,ar.length-1);
System.out.println(Iswaps - Qswaps);
}
static void quicksort(int[] array, int beg, int end)
{
if(beg >= end) return;
int pivot = array[end];
int wall = beg;
//Partition with a wall
for(int i = beg; i < end; i++)
{
if(array[i] < pivot)
{
swap(array, i, wall);
wall++;
}
}
//Place pivot
swap(array, end, wall);
//Sort left of partition
quicksort(array, beg, wall-1);
//Sort right of partition
quicksort(array, wall+1, end);
}
static void swap(int[] array, int index1, int index2)
{
int tmp = array[index1];
array[index1] = array[index2];
array[index2] = tmp;
Qswaps++;
}
static void printArray(int[] array)
{
for(int num : array)
{
System.out.print(num+" ");
}
System.out.println("");
}
public static void insertionSort(int[] A){
for(int i = 0; i < A.length; i++){
int value = A[i];
int j = i - 1;
while(j >= 0 && A[j] > value){
A[j + 1] = A[j];
j = j - 1;
}
A[j + 1] = value;
Iswaps += i - (j+1);
}
}
}