Quick select sort








**QuickSelect:**

   - **Purpose:** QuickSelect is an algorithm used for finding the k-th smallest element in an unordered list.

   - **Algorithm:** It is a variation of the quicksort algorithm but focuses on only one partition, depending on the position of the desired element relative to the pivot.

   - **Efficiency:** On average, QuickSelect has linear time complexity O(n), making it efficient for finding the k-th element without fully sorting the entire list.

 **QuickSort:**

   - **Purpose:** QuickSort is a sorting algorithm that efficiently sorts an array or list of elements.

   - **Algorithm:** It follows the divide-and-conquer paradigm, selecting a 'pivot' element and partitioning the other elements into two sub-arrays according to whether they are less than or greater than the pivot.

   - **Efficiency:** QuickSort is known for its average-case time complexity of O(n log n), making it faster in practice compared to many other sorting algorithms.


In summary, QuickSelect is primarily used for finding the k-th smallest element, while QuickSort is a general-purpose sorting algorithm. Both algorithms are based on the same partitioning technique, making them efficient for their respective tasks.




### QuickSelect Algorithm:


1. **Choose a Pivot:**

   - Select a pivot element from the array. The choice of the pivot can be random, but for simplicity, let's assume we always choose the last element.


2. **Partition the Array:**

   - Rearrange the elements in the array so that elements smaller than the pivot are on the left, and elements greater than the pivot are on the right. The pivot is now in its final sorted position.


3. **Recursively Select a Subarray:**

   - If the pivot's index is equal to the desired index (k), then we have found the k-th smallest element.

   - If the pivot's index is less than k, then the desired element is in the right subarray, and we recursively apply QuickSelect to that subarray.

   - If the pivot's index is greater than k, then the desired element is in the left subarray, and we recursively apply QuickSelect to that subarray.


4. **Repeat Until Found:**

   - Repeat steps 1-3 until the desired element is found.


### Example:


Let's consider an array `[5, 2, 8, 1, 6, 3]` and find the 3rd smallest element (k = 3).


1. **Initial Array:** `[5, 2, 8, 1, 6, 3]` (Choose pivot: 3)


2. **After Partitioning:** `[2, 1, 3, 5, 6, 8]` (Pivot 3 is in its final position)


3. **Recursion:**

   - Since the pivot's index (3) is equal to k (3), we have found the 3rd smallest element, which is 3.


   The algorithm stops, and the result is 3, the 3rd smallest element in the array.


In each step, the algorithm reduces the problem size by dividing the array into two parts, depending on the position of the pivot. This process continues until the desired element is found without the need to fully sort the entire array.




```c

#include <stdio.h>


// Function to swap two elements in an array

void swap(int *a, int *b) {

    int temp = *a;

    *a = *b;

    *b = temp;

}


// Function to perform the partition step of QuickSelect

int partition(int arr[], int low, int high) {

    int pivot = arr[high];  // Choose the pivot (last element)

    int i = low - 1;


    for (int j = low; j < high; j++) {

        if (arr[j] < pivot) {

            i++;

            swap(&arr[i], &arr[j]);

        }

    }


    swap(&arr[i + 1], &arr[high]); // Swap pivot to its final position

    return i + 1;

}


// Function to perform QuickSelect

int quickSelect(int arr[], int low, int high, int k) {

    if (low <= high) {

        // Perform partitioning

        int pivotIndex = partition(arr, low, high);


        // Check if the pivot is the k-th smallest element

        if (pivotIndex == k)

            return arr[pivotIndex];


        // If k is smaller, recur in the left subarray

        if (pivotIndex > k)

            return quickSelect(arr, low, pivotIndex - 1, k);


        // Else recur in the right subarray

        return quickSelect(arr, pivotIndex + 1, high, k);

    }


    // Return -1 if k is out of bounds

    return -1;

}


int main() {

    int arr[] = {5, 2, 8, 1, 6, 3};

    int n = sizeof(arr) / sizeof(arr[0]);

    int k = 2; // Find the 3rd smallest element (k = 2)


    int result = quickSelect(arr, 0, n - 1, k);

    

    if (result != -1)

        printf("The %d-th smallest element is: %d\n", k + 1, result);

    else

        printf("Invalid value of k\n");


    return 0;

}

```


This code defines a `quickSelect` function that takes an array, its lower and upper bounds, and the value of k. The example is set up to find the 3rd smallest element (k = 2) in the provided array `[5, 2, 8, 1, 6, 3]`. Note that array indices start from 0, so we print the (k + 1)-th smallest element.



output:

The 3-th smallest element is: 3


Process returned 0 (0x0)   execution time : 0.030 s

Press any key to continue.


The choice between QuickSort and QuickSelect depends on the specific requirements of the task at hand.


### QuickSort:

- **Advantages:**

  - Efficient for sorting entire arrays or lists.

  - Average time complexity of O(n log n), which is quite good.

  - In-place sorting, requiring only a small amount of additional memory.


- **Disadvantages:**

  - If the array is already partially sorted, QuickSort might not perform optimally.

  - In the worst case, QuickSort has a time complexity of O(n^2) if poor pivot choices are made.


### QuickSelect:

- **Advantages:**

  - Efficient for finding the k-th smallest or largest element without fully sorting the array.

  - Average time complexity of O(n), making it linear for the specific task of selection.

  - Can be faster than QuickSort when only a few elements are needed.


- **Disadvantages:**

  - Does not provide a fully sorted array.

  - Performance can degrade if poor pivot choices are consistently made, leading to a less balanced partition.


### Conclusion:

- If your primary goal is to fully sort an array, QuickSort is a good choice due to its average-case time complexity and in-place sorting capability.

  

- If you are interested in finding specific elements (like the k-th smallest element) and do not require a fully sorted array, QuickSelect can be more efficient, especially for large datasets.


In summary, the better algorithm depends on the specific requirements of your task. If sorting is the primary goal, QuickSort is a solid choice. If selection is the main focus, QuickSelect is often more efficient. Keep in mind that there are other sorting and selection algorithms with different characteristics, and the best choice depends on the specific context and constraints of your problem.





Post a Comment

0 Comments