Sorting Techniques
Sorting Techniques
Sorting Techniques
• Bubble Sort.
• Selection Sort.
• Merge Sort.
• Insertion Sort.
• Quick Sort.
• Heap Sort
Time Complexities of all Sorting
Algorithms
Algorithm Time Complexity
}
• The time complexity of quicksort is dependent
upon the partition and how sorted the list
already is.
• There are some cases where we’re likely to fall
into the trap of choosing a pivot that’s not
near the median of a dataset. In fact, we kind
of fell right into this trap just now!
• For arrays that are nearly or completely
sorted, quicksort operates at its worst. In
other words, the average runtime for a sorted
or a nearly-sorted list is quicksort’s worst case
runtime: O(n²).
• This is particularly important to remember if
we know that we’ll be dealing with data that’s
mostly sorted. In those situations, we want to
stay away from quicksort, since it’s going to
take a really long time to run.
Merge Sort
}
void merge(int first,int last)
{
int b[10],mid,i1,i2,i3,k,k1;
mid=(first+last)/2;
i1=first;
i2=mid+1;
i3=0;
while(i1<=mid&&i2<=last)
{
if(a[i1]<a[i2])
b[i3++]=a[i1++];
else
b[i3++]=a[i2++];
}
for(;i1<=mid;)
b[i3++]=a[i1++];
for(;i2<=last;)
b[i3++]=a[i2++];
for(k=first,k1=0;k<=last;k++,k1++)
a[k]=b[k1];
}
• The time complexity of merge sort is O(n log
n). Recursive nature of merge sort results for
O(n log n). Each Recursive call has O(n) steps
and there are log n steps to get the final
solution. so, it results for O(n log n).
Practice Problem
• Given an array A[] and a number x, check for
pair in A[] with sum as x
• Write a C program that, given an array A[] of n
numbers and another number x, determines
whether or not there exist two elements in S
whose sum is exactly x.
Algorithm:
getchar();
return 0;
}
/* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING
PURPOSE */
void exchange(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
• 1 ≤ T ≤ 10
• 2 ≤ N, M ≤ 105
• 0 ≤ Q ≤ 105
• 1≤X≤N
• 1≤Y≤M
• 0 ≤ sum of Q over all test cases
Note: