Sorting Techs (1)
Sorting Techs (1)
Selection Sort
n = 7;
for (i = 0; i < n - 1; i++)
{ printf("Sorted array: ");
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1]) for ( i = 0; i < n; i++)
{ {
temp = arr[j]; printf("%d ", arr[i]);
arr[j] = arr[j + 1]; }
arr[j + 1] = temp;
}
return 0;
} }
}
3.Insertion Sort
-Works by iterating through the array one element at
a time, inserting each element into its proper
position within the previously sorted portion of the
array.
- Time complexity: O(n^2)
-Space complexity: O(1)
- Example:
Original array: [5, 2, 4, 6, 1, 3]
Sorted array: [1, 2, 3, 4, 5, 6]
/*3. Insertion Sort
Insertion sort is a simple sorting algorithm that builds the final sorted array (or
list) one item at a time.
*/
#include <stdio.h>
int main()
{
int arr[] = {4,3,1,2,5};
int n = sizeof(arr) / sizeof(arr[0]); printf("Sorted array: ");
int i, key, j;
for (i = 1; i < n; i++) for ( i = 0; i < n; i++)
{ {
key = arr[i]; printf("%d ", arr[i]);
j = i - 1; }
while (j >= 0 && arr[j] > key) return 0;
{ }
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
4. Quick Sort:
QuickSort is a sorting algorithm based on the Divide and
Conquer algorithm that picks an element as a pivot and
partitions the given array around the picked pivot by placing
the pivot in its correct position in the sorted array.
- Example:
Original array: [5, 2, 4, 6, 1, 3]
Sorted array: [1, 2, 3, 4, 5, 6]
//Quick Sort
#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
} // Function to partition the array
int partition(int arr[], int low, int high)
{
int pivot = arr[high]; // Choose the last element as the pivot
int i = low - 1;
int i = 0, j = 0, k = left;
// Merge the temporary arrays
while (i < n1 && j < n2)
{
if (leftArr[i] <= rightArr[j])
{
arr[k] = leftArr[i]; // Copy remaining elements of rightArr[], if there are any
i++; while (j < n2)
} {
else arr[k] = rightArr[j];
{ j++;
arr[k] = rightArr[j]; k++;
j++; }
} }
k++;
}
// Copy remaining elements of leftArr[], if there are any
while (i < n1)
{
arr[k] = leftArr[i];
i++;
k++;
}
// Function to implement Merge Sort
void mergeSort(int arr[], int left, int right)
{
if (left < right)
{
int mid = left + (right - left) / 2;