Bạn đang xem: Sort colors

Sorts are most commonly in numerical or a khung of alphabetical (called lexicographical) order, và can be in ascending (A-Z, 0-9) or descending (Z-A, 9-0) order.

Since sorting can often reduce the complexity of a problem, it is an important algorithm in Computer Science. These algorithms have direct applications in searching algorithms, database algorithms, divide và conquer methods, data structure algorithms, and many more.

When using different algorithms some questions have sầu to be asked. How big is the collection being sorted? How much memory is at disposal to lớn be used? Does the collection need lớn grow?

The answers to lớn these questions may determine what algorithm is going to work best for the situation. Some algorithms lượt thích merge sort may need a lot of space khổng lồ run, while insertion sort is not always the faschạy thử but it doesn"t require many resources to run.

You should determine what the requirements of the system are and its limitations before deciding what algorithm to lớn use.

Some of the most comtháng sorting algorithms are:

Selection SortBubble SortInsertion SortMerge SortQuiông xã SortHeap SortCounting SortRadix SortBucket SortBut before we get inlớn each of these, let"s learn a bit more about what makes classifies a sorting algorithm.

Sorting algorithms can be categorized based on the following parameters:

Based on Number of Swaps or Inversion This is the number of times the algorithm swaps elements khổng lồ sort the input. Selection Sort requires the minimum number of swaps.Based on Recursion or Non-Recursion Some sorting algorithms, such as Quick Sort , use recursive techniques to sort the đầu vào. Other sorting algorithms, such as Selection Sort or Insertion Sort , use non-recursive sầu techniques. Finally, some sorting algorithm, such as Merge Sort , make use of both recursive sầu as well as non-recursive sầu techniques khổng lồ sort the đầu vào.Based on Stability Sorting algorithms are said to lớn be stable if the algorithm maintains the relative sầu order of elements with equal keys. In other words, two equivalent elements remain in the same order in the sorted output as they were in the input.Insertion sort , Merge Sort , and Bubble Sort are stableHeap Sort & Quiông xã Sort are not stableBased on Extra Space Requirement Sorting algorithms are said lớn be in place if they require a constant O(1) extra space for sorting.Insertion sort & Quick-sort are in place sort as we move sầu the elements about the pivot và do not actually use a separate array which is NOT the case in merge sort where the form size of the đầu vào must be allocated beforehand lớn store the output during the sort.Merge Sort is an example of out place sort as it require extra memory space for its operations.Any comparison based sorting algorithm must make at least nLog2n comparisons to sort the input đầu vào array, & Heapsort và merge sort are asymptotically optimal comparison sorts. This can be easily proved by drawing a decision tree diagram.

Bucket Sort is a comparison sort algorithm that operates on elements by dividing them into different buckets và then sorting these buckets individually. Each bucket is sorted individually using a separate sorting algorithm or by applying the bucket sort algorithm recursively.

Bucket Sort is mainly useful when the input is uniformly distributed over a range.

You have sầu been given a large array of floating point integers lying uniformly between the lower and upper bound. This array now needs khổng lồ be sorted.

A simple way to solve this problem would be lớn use another sorting algorithm such as Merge sort, Heap Sort or Quiông chồng Sort. However, these algorithms guarantee a best case time complexity of O(NlogN). However, using bucket sort, the above task can be completed in O(N)time.

Let"s have a closer look at it.

Consider that you need to lớn create an array of lists, that is of buckets. Elements now need to be inserted into lớn these buckets on the basis of their properties. Each of these buckets can then be sorted individually using Insertion Sort.

void bucketSort(float<> a,int n) for(each floating integer "x" in n) insert x inlớn bucket

For simplithành phố, consider the data in the range 0 khổng lồ 9. Input data: 1, 4, 1, 2, 7, 5, 2 1) Take a count array to store the count of each chất lượng object. Index: 0 1 2 3 4 5 6 7 8 9 Count: 0 2 2 0 1 1 0 1 0 0 2) Modify the count array such that each element at each index stores the sum of previous counts. Index: 0 1 2 3 4 5 6 7 8 9 Count: 0 2 4 4 5 6 6 7 7 7The modified count array indicates the position of each object in the output sequence. 3) đầu ra each object from the input đầu vào sequence followed by decreasing its count by 1. Process the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 2. Put data 1 at index 2 in output. Decrease count by 1 to lớn place next data 1 at an index 1 smaller than this index.

In Insertion sort, you compare the key element with the previous elements. If the previous elements are greater than the key element, then you move the previous element to the next position.

Start from index 1 khổng lồ form size of the đầu vào array.

< 8 3 5 1 4 2 >

Step 1 :

" width="242" height="47" loading="lazy">key = 3 //starting from 1st index. Here `key` will be compared with the previous elements. In this case, `key` is compared with 8. since 8 > 3, move the element 8 lớn the next position và insert `key` to the previous position. Result: < 3 8 5 1 4 2 >Step 2 :

" width="242" height="75" loading="lazy">key = 5 //2nd index 8 > 5 //move sầu 8 to 2nd index và insert 5 to lớn the 1st index. Result: < 3 5 8 1 4 2 >Step 3 :

" width="242" height="73" loading="lazy">key = 1 //3rd index 8 > 1 => < 3 5 1 8 4 2 > 5 > 1 => < 3 1 5 8 4 2 > 3 > 1 => < 1 3 5 8 4 2 > Result: < 1 3 5 8 4 2 >Step 4 :

" width="242" height="73" loading="lazy">key = 4 //4th index 8 > 4 => < 1 3 5 4 8 2 > 5 > 4 => < 1 3 4 5 8 2 > 3 > 4 ≠> stop Result: < 1 3 4 5 8 2 >Step 5 :

" width="242" height="62" loading="lazy">key = 2 //5th index 8 > 2 => < 1 3 4 5 2 8 > 5 > 2 => < 1 3 4 2 5 8 > 4 > 2 => < 1 3 2 4 5 8 > 3 > 2 => < 1 2 3 4 5 8 > 1 > 2 ≠> stop Result: <1 2 3 4 5 8>

" width="242" height="63" loading="lazy">The algorithm shown below is a slightly optimized version lớn avoid swapping the key element in every iteration. Here, the key element will be swapped at the kết thúc of the iteration (step). InsertionSort(arr<>) for j = 1 to arr.length key = arr* > key arr = arr i = i - 1 arr = keyHere is a detailed implementation in JavaScript:*

*function insertion_sort(A) var len = array_length(A); var i = 1; while (i = 0 &và A > x) A = A; j = j - 1; A = x; i = i + 1; }A quichồng implementation in Swift is shown below:*

* var array = <8, 3, 5, 1, 4, 2> func insertionSort(array:inout Array) -> Array for j in 0.. 0 &và array > key) array = array i = i-1 array = key return array }The Java example is shown below:*

*public int<> insertionSort(int<> arr) for (j = 1; j 0 & arr > key) arr = arr i -= 1 arr = key } return arr;And in c....*

*void insertionSort(int arr<>, int n) int i, key, j; for (i = 1; i = 0 &và arr > key) arr = arr; j = j-1; arr = key; } *

This property can be leveraged to access the maximum element in the heap in O(logn) time using the maxHeapify method. We perform this operation n times, each time moving the maximum element in the heap lớn the top of the heap & extracting it from the heap & into a sorted array. Thus, after n iterations we will have a sorted version of the input đầu vào array.

The algorithm is not an in-place algorithm và would require a heap data structure to lớn be constructed first. The algorithm is also unstable, which means when comparing objects with same key, the original ordering would not be preserved.

This algorithm runs in O(nlogn) time and O(1) additional space

The best, worst and average case time complexity of Heapsort is O(nlogn). Although heapsort has a better worse-case complexity than quicksort, a well-implemented quicksort runs faster in practice. This is a comparison-based algorithm so it can be used for non-numerical data sets insofar as some relation (heap property) can be defined over the elements.

An implementation in Java is as shown below :

import java.util.Arrays;public class Heapsort public static void main(String<> args) //kiểm tra arrayInteger<> arr = 1, 4, 3, 2, 64, 3, 2, 4, 5, 5, 2, 12, 14, 5, 3, 0, -1;String<> strarr = "hope you find this helpful!", "wef", "rg", "q2rq2r", "avs", "erhijer0g", "ewofij", "gwe", "q", "random";arr = heapsort(arr);strarr = heapsort(strarr);System.out.println(Arrays.toString(arr));System.out.println(Arrays.toString(strarr));//O(nlogn) TIME, O(1) SPACE, NOT STABLEpublic static > E<> heapsort(E<> arr)int heaplength = arr.length;for(int i = arr.length/2; i>0;i--)arr = maxheapify(arr, i, heaplength);for(int i=arr.length-1;i>=0;i--)E max = arr<0>;arr<0> = arr*;arr = max;heaplength--;arr = maxheapify(arr, 1, heaplength);return arr;//Creates maxheap from arraypublic static > E<> maxheapify(E<> arr, Integer node, Integer heaplength)Integer left = node*2;Integer right = node*2+1;Integer largest = node;if(left.compareTo(heaplength) = 0)largest = left;if(right.compareTo(heaplength) = 0)largest = right;if(largest != node)E temp = arr*

*#include using namespace std;void heapify(int arr<>, int n, int i) int largest = i; int l = 2*i + 1; int r = 2*i + 2; if (l arr ) largest = l; if (r arr) largest = r; if (largest != i) swap(arr*

QuickSort, MergeSort, and HeapSort are comparison-based sorting algorithms. CountSort is not. It has the complexity of O(n+k), where k is the maximum element of the đầu vào array. So, if k is O(n), CountSort becomes linear sorting, which is better than comparison based sorting algorithms that have O(nlogn) time complexity.

The idea is lớn extkết thúc the CountSort algorithm to get a better time complexity when k goes O(n2). Here comes the idea of Radix Sort.

For each digit i where i varies from the least significant digit to lớn the most significant digit of a number, sort input đầu vào array using countsort algorithm according to lớn ith digit. We used count sort because it is a stable sort.

Example: Assume the đầu vào array is:

10, 21, 17, 34, 44, 11, 654, 123

Based on the algorithm, we will sort the đầu vào array according lớn the one"s digit (least significant digit).

0: 101: 21 112:3: 1234: 34 44 6545:6:7: 178:9:

So, the array becomes 10, 21, 11, 123, 24, 44, 654, 17.

Now, we"ll sort according to the ten"s digit:

0:1: 10 11 172: 21 1233: 344: 445: 6546:7:8:9:

Now, the array becomes : 10, 11, 17, 21, 123, 34, 44, 654.

Finally, we sort according lớn the hundred"s digit (most significant digit):

0: 010 011 017 021 034 0441: 1232:3:4:5:6: 6547:8:9:

The array becomes : 10, 11, 17, 21, 34, 44, 123, 654 which is sorted. This is how our algorithm works.

Xem thêm: Biec Ron Là Gì - Ý Nghĩa Tượng Trưng Biếc Rờn

An implementation in C:

void countsort(int arr<>,int n,int place){ int i,freq*; freq<(arr /place)%range>--; for(i=0;i*

Here"s how it works:

Find the smallest element in the array và swap it with the first element.Find the second smallest element và swap with with the second element in the array.Find the third smallest element and swap wit with the third element in the array.Repeat the process of finding the next smallest element và swapping it into lớn the correct position until the entire array is sorted.But, how would you write the code for finding the index of the second smallest value in an array?

An easy way is khổng lồ notice that the smallest value has already been swapped inkhổng lồ index 0, so the problem reduces to finding the smallest element in the array starting at index 1.

Selection sort always takes the same number of key comparisons — N(N − 1)/2.

The following C++ program contains an iterative as well as a recursive sầu implementation of the Selection Sort algorithm. Both implementations are invoked in the main() function.

#include #include using namespace std;templatevoid print_array(T const(&arr)

With a worst-case complexity of O(n^2), bubble sort is very slow compared lớn other sorting algorithms lượt thích quicksort. The upside is that it is one of the easiest sorting algorithms to lớn underst& & code from scratch.

From technical perspective, bubble sort is reasonable for sorting small-sized arrays or specially when executing sort algorithms on computers with remarkably limited memory resources.

The danh mục is already sorted, but the bubble sort algorithm doesn"t realize this. Rather, it needs to lớn complete an entire pass through the menu without swapping any values lớn know the list is sorted.

Clearly bubble sort is far from the most efficient sorting algorithm. Still, it"s simple khổng lồ wrap your head around and implement yourself.

PropertiesSpace complexity: O(1)Best case performance: O(n)Average case performance: O(n*n)Worst case performance: O(n*n)Stable: YesBubble sort algorithm

let arr = <1, 4, 7, 45, 7,43, 44, 25, 6, 4, 6, 9>, sorted = false;while(!sorted) sorted = true; for(var i=0; i

For instance, the time complexity of Quick Sort is approximately O(nlog(n)) when the selection of pivot divides original array inlớn two nearly equal sized sub arrays.

On the other hvà, if the algorithm, which selects of pivot element of the input đầu vào arrays, consistently outputs 2 sub arrays with a large difference in terms of array sizes, quichồng sort algorithm can achieve sầu the worst case time complexity of O(n^2).

The steps involved in Quichồng Sort are:

Choose an element khổng lồ serve sầu as a pivot, in this case, the last element of the array is the pivot.Partitioning: Sort the array in such a manner that all elements less than the pivot are to the left, and all elements greater than the pivot are to the right.hotline Quicksort recursively, taking into lớn account the previous pivot to lớn properly subdivide the left và right arrays. (A more detailed explanation can be found in the comments below)const arr = <6, 2, 5, 3, 8, 7, 1, 4>;const quickSort = (arr, start, end) => if(start let pivot = end; // Set i to start - 1 so that it can access the first index in the sự kiện that the value at arr<0> is greater than arr* will be a value greater than arr ) & swap the value at arr*

Quick sort achieves this by changing the order of elements within the given array. Compare this with the merge sort algorithm which creates 2 arrays, each length n/2, in each function call.

However there does exist the problem of this sorting algorithm being of time O(n*n) if the pivot is always kept at the middle. This can be overcomed by utilizing a random pivot

Best, average, worst, memory: ** **n log(n)n log(n)n 2log(n). It"s not a stable algorithm, và quicksort is usually done in-place with O(log(n)) staông chồng space.

The space complexity of quick sort is O(n). This is an improvement over other divide and conquer sorting algorithms, which take O(n log(n)) space.

Timsort is a fast sorting algorithm working at stable O(N log(N)) complexity.

Timsort is a blover of Insertion Sort & Mergesort. This algorithm is implemented in Java’s Arrays.sort() as well as Python’s sorted() & sort(). The smaller parts are sorted using Insertion Sort và are later merged together using Mergesort.

A quiông xã implementation in Python:

def binary_search(the_array, chiến thắng, start, end): if start == end: if the_array

Merge Sort is a Divide và Conquer algorithm. It divides input đầu vào array in two halves, calls itself for the two halves & then merges the two sorted halves. The major portion of the algorithm is given two sorted arrays, and we have sầu to merge them inlớn a single sorted array. The whole process of sorting an array of N integers can be summarized inlớn three steps-

Divide the array into two halves.Sort the left half and the right half using the same recurring algorithm.Merge the sorted halves.There is something known as the Two Finger Algorithm that helps us merge two sorted arrays together. Using this subroutine & calling the merge sort function on the array halves recursively will give us the final sorted array we are looking for.

Since this is a recursion based algorithm, we have a recurrence relation for it. A recurrence relation is simply a way of representing a problem in terms of its subproblems.

T(n) = 2 * T(n / 2) + O(n)

Putting it in plain English, we break down the subproblem inkhổng lồ two parts at every step và we have sầu some linear amount of work that we have sầu to vày for merging the two sorted halves together at each step.

The biggest advantage of using Merge sort is that the time complexity is only n*log(n) lớn sort an entire Array. It is a lot better than n^2 running time of bubble sort or insertion sort.

Before we write code, let us underst& how merge sort works with the help of a diagram.

Initially we have an array of 6 unsorted integers Arr(5, 8, 3, 9, 1, 2)We split the array inlớn two halves Arr1 = (5, 8, 3) & Arr2 = (9, 1, 2).Again, we divide them into lớn two halves: Arr3 = (5, 8) and Arr4 = (3) & Arr5 = (9, 1) & Arr6 = (2)Again, we divide them into two halves: Arr7 = (5), Arr8 = (8), Arr9 = (9), Arr10 = (1) and Arr6 = (2)We will now compare the elements in these sub arrays in order to merge them.void merge(int array<>, int left, int mid, int right){ int i, j, k; // Size of left sublistint size_left = mid - left + 1;// Size of right sublistint size_right = right - mid;/* create temp arrays */int Left

function merge (a,b) { var result = <>; while (a.length >0 && b.length >0) result.push(a<0> When we merge the two halfs, we store the result in an auxilliary array. We will compare the starting element of left array lớn the starting element of right array. Whichever is lesser will be pushed inkhổng lồ the results array và we will remove it from there respective arrays using

var demo = <5,6,7,3,1,3,15>;console.log(mergeSort(test));>> <1, 3, 3, 5, 6, 7, 15>

const danh mục = <23, 4, 42, 15, 16, 8, 3>const mergeSort = (list) =>{ if(các mục.length { var result = <>; while(left.length || right.length) { if(left.length && right.length) { if(left<0>

void mergesort(int A<>,int size_a,int B<>,int size_b,int C<>){ int token_a,token_b,token_c; for(token_a=0, token_b=0, token_c=0; token_a