daa2
daa2
Experiment no. :- 02
1. Theory :
Quick Sort is a highly efficient sorting algorithm based on the divide-and-conquer paradigm. It works
by selecting a pivot element from the array and partitioning the other elements into two sub-arrays: one
with elements less than the pivot and the other with elements greater than the pivot. The process is then
repeated recursively for the sub-arrays.
Randomized Quick Sort is a variation of Quick Sort where the pivot is chosen randomly. This
randomization helps to avoid the worst-case scenario (O(n²)) that occurs in Quick Sort when the pivot is
consistently the smallest or largest element in the array. On average, both algorithms have a time
complexity of O(n log n).
The problem statement involves implementing and analyzing both Quick Sort and Randomized Quick
Sort to compare their performance in terms of time complexity and practical execution time.
a) Quick Sort:
Pseudo Code :
Pseudo Code :
Time Complexity:
Best Case: O(n log n) - Occurs when the pivot divides the array into two nearly equal parts.
Average Case: O(n log n) - Expected case for Randomized Quick Sort.
Worst Case: O(n²) - Occurs in Quick Sort when the pivot is consistently the smallest or largest
element. Randomized Quick Sort mitigates this by randomizing pivot selection.
Space Complexity:
O(log n) - Due to the recursive call stack.
import java.util.Scanner;
// Partition function
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high]; // Choose the last element as the pivot
int i = low - 1; // Index of the smaller element
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j); // Swap arr[i] and arr[j]
}
}
swap(arr, i + 1, high); // Swap arr[i+1] and arr[high] (pivot)
return i + 1;
}
System.out.println("Original array:");
printArray(arr);
quickSort(arr, 0, n - 1);
scanner.close();
}
}
Result:
import java.util.Random;
import java.util.Scanner;
// Partition function
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high]; // Choose the last element as the pivot
int i = low - 1; // Index of the smaller element
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j); // Swap arr[i] and arr[j]
}
}
swap(arr, i + 1, high); // Swap arr[i+1] and arr[high] (pivot)
return i + 1;
}
System.out.println("Original array:");
printArray(arr);
randomizedQuickSort(arr, 0, n - 1);
scanner.close();
}
}
Result:-
5. Conclusion:
Quick Sort and Randomized Quick Sort are both efficient sorting algorithms with an average time
complexity of O(n log n). While Quick Sort is simpler and faster in most cases, Randomized Quick Sort
provides a more robust solution by reducing the likelihood of worst-case performance. The choice
between the two depends on the specific use case and the nature of the input data. For general-purpose
sorting, Randomized Quick Sort is often preferred due to its consistent performance..