You are on page 1of 5

LAB EXAM CS263

Dev Juneja
202011020
Question 2

Code :

import java.util.*;

public class Main {


public class QuickSort {

public int[] quickSort(int[] arr) {


quickSort(arr, 0, arr.length);
return arr;
}

public void quickSort(int[] arr, int low, int high) {


if (low < high) {
int i = low + 1, j = high;
int p = arr[low];
int pLow = low, pHigh = low;
if(i<arr.length){
do {
if (arr[i] < p) {
int t = arr[i];
int d;
for (d = pHigh; d>= pLow; d--)
arr[d + 1] = arr[d];
arr[++d] = t;
pHigh++;
pLow++;
i++;
} else if (arr[i] == p) {
pHigh++;
i++;
} else {
while (j > i) {
j--;
if (arr[j] < arr[i]) {
int t = arr[j];
arr[j] = arr[i];
arr[i] = t;
break;
}
}
}
} while (i < j);
quickSort(arr, low, pLow);
quickSort(arr, pHigh + 1, high);
}
}
}
}

public int [] arr;

public Main(int [] arr){


this.arr = arr;
}

public void sort(){


new QuickSort().quickSort(arr);
}

public int [] remoDupEle(){


sort();
ArrayList<Integer> result = new ArrayList<>();
result.add(arr[0]);
for(int i = 1; i<arr.length; i++){
if(arr[i]>arr[i-1]){
result.add(arr[i]);
}
}
int [] getArray = new int[result.size()];
for(int i = 0; i<getArray.length; i++)
getArray[i] = result.get(i);
return getArray;

}
public static void main(String[] args) {
int [] arr = {5,4,3,5,3,2,5,1,1,7,1,2,3,3,3,6};
int [] newArr = new Main(arr).remoDupEle();
System.out.println(Arrays.toString(newArr));
}
}
Output :

Algorithm :

Quick Sort :

 Take first element of the list as pivot (i.e., Element at first


position in the list).

 Assume two variables i and j. Set i and j to be the first and


the last elements of the list respectively

 Increment i until list[i] > pivot then stop.


 Decrement j until list[j] < pivot then stop.

 If i < j then swap list[i] and list[j].

 Using recursion repeat steps 3,4 & 5 until i > j.

 Swap the pivot element with list[j] element.

Removing duplicate elements :

 Sort the array using quick sort.

 Iterate the sorted array.

 Check the condition (arr[i]>arr[i-1]).

 If the above condition is true, store the element in array


list.

 Return the array list.

Time complexity to solve the given problem using the above


procedure is O(nlogn).

Explanation :
Time complexity of sorting elements is O(nlogn) (quick sort).
After sorting, finding duplicate elements will take the time
complexity of O(n). Therefore, the overall complexity of this
algorithm will be O(nlogn).

Assumption:
Input must be an Integer Array

You might also like