Junior — Middle
Can you list the main data sorting methods you know?
sobes.tech AI
Answer from AI
Main data sorting methods that are commonly used:
- Bubble Sort — a simple but inefficient method that compares neighboring elements and swaps them.
- Insertion Sort — effective for nearly sorted data, inserts elements into an already sorted part.
- Selection Sort — finds the minimum element and places it at the beginning.
- Merge Sort — recursively divides the array into parts, sorts and merges them; stable and efficient.
- Quick Sort — chooses a pivot element and divides the array into parts; usually very fast in practice.
- Heap Sort — uses a heap data structure for sorting.
Example of quick sort in Python:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
print(quick_sort([3,6,8,10,1,2,1]))