Posted on

# List of Sorting Algorithms w/ Code Examples in Python and Ruby

There are numerous sorting algorithms, each with its own characteristics and advantages depending on the specific requirements and constraints of a given problem. Here is a list of some common sorting algorithms:

1. Bubble Sort: Compares adjacent elements and swaps them if they are in the wrong order. Repeats this process until no swaps are needed.
2. Selection Sort: Divides the input list into a sorted and an unsorted region. It repeatedly selects the minimum element from the unsorted region and moves it to the sorted region.
3. Insertion Sort: Builds the final sorted array one item at a time by repeatedly taking an element from the unsorted part and inserting it into its correct position in the sorted part.
4. Merge Sort: Divides the input list into two halves, sorts each half, and then merges the two sorted halves into a single sorted list.
5. Quick Sort: Chooses a pivot element and partitions the array into two sub-arrays: elements less than the pivot and elements greater than the pivot. It then recursively sorts the sub-arrays.
6. Heap Sort: Builds a binary heap from the input data and repeatedly removes the maximum element from the heap and adds it to the sorted list.
7. Counting Sort: Suitable for sorting integers within a known range. It counts the occurrences of each element and uses that information to place elements in the correct order.
8. Radix Sort: Sorts integers by processing individual digits from the least significant to the most significant. It can be used for integers represented in base 10 or other bases.
9. Bucket Sort: Distributes elements into a finite number of buckets and then sorts each bucket individually, either using a different sorting algorithm or by recursively applying bucket sort.
10. Tim Sort: A hybrid sorting algorithm derived from merge sort and insertion sort. It is designed to perform well on many kinds of real-world data.
11. Shell Sort: An extension of insertion sort that divides the input into smaller sub-arrays and sorts each sub-array using insertion sort.
12. Cocktail Shaker Sort: Similar to bubble sort but sorts in both directions, moving the largest and smallest elements to their correct positions.
13. Bogo Sort: A highly inefficient and random sorting algorithm that generates random permutations of the input until it happens to be sorted.
14. Pancake Sort: A sorting algorithm that only allows flipping sections of the array in order to sort it.
15. Cycle Sort: A sorting algorithm that minimizes the number of writes to the data store and is useful for sorting data with expensive write operations.
16. Stooge Sort: A recursive sorting algorithm that sorts a list by recursively sorting the first two-thirds and the last two-thirds of the list and then sorting the first two-thirds again.

These are just some of the many sorting algorithms available. The choice of which algorithm to use depends on factors such as the size of the data, the distribution of values, memory constraints, and the desired time complexity.

## Sorting Algorithms Code Example in Python

Certainly! Here are Python 3 implementations of various sorting algorithms:

1. Bubble Sort:
``````def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]  # Swap elements
swapped = True
if not swapped:
break
return arr``````
1. Selection Sort:
``````def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]  # Swap elements
return arr``````
1. Insertion Sort:
``````def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr``````
1. Merge Sort:
``````def merge_sort(arr):
if len(arr) <= 1:
return arr

mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

left_half = merge_sort(left_half)
right_half = merge_sort(right_half)

return merge(left_half, right_half)

def merge(left, right):
result = []
i = j = 0

while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1

result.extend(left[i:])
result.extend(right[j:])
return result``````
1. Quick Sort:
``````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)``````

You can use these functions to sort lists of elements by passing the list as an argument to the respective sorting function.

## Sorting Algorithms Code Example in Ruby

Implementing sorting algorithms in Ruby can be a great way to learn and practice algorithmic concepts. Here, I’ll provide a basic outline for implementing some common sorting algorithms in Ruby. You can use these outlines as a starting point and then write the actual Ruby code for each algorithm based on these descriptions.

1. Bubble Sort:
``````   def bubble_sort(arr)
n = arr.length
loop do
swapped = false
(n - 1).times do |i|
if arr[i] > arr[i + 1]
arr[i], arr[i + 1] = arr[i + 1], arr[i] # Swap elements
swapped = true
end
end
break unless swapped
end
arr
end``````
1. Selection Sort:
``````   def selection_sort(arr)
n = arr.length
(n - 1).times do |i|
min_index = i
(i + 1...n).each do |j|
min_index = j if arr[j] < arr[min_index]
end
arr[i], arr[min_index] = arr[min_index], arr[i] # Swap elements
end
arr
end``````
1. Insertion Sort:
``````   def insertion_sort(arr)
n = arr.length
(1...n).each do |i|
key = arr[i]
j = i - 1
while j >= 0 && arr[j] > key
arr[j + 1] = arr[j]
j -= 1
end
arr[j + 1] = key
end
arr
end``````
1. Merge Sort:
``````   def merge_sort(arr)
return arr if arr.length <= 1

mid = arr.length / 2
left_half = merge_sort(arr[0...mid])
right_half = merge_sort(arr[mid..-1])

merge(left_half, right_half)
end

def merge(left, right)
result = []
until left.empty? || right.empty?
result << (left.first <= right.first ? left.shift : right.shift)
end
result.concat(left).concat(right)
end``````
1. Quick Sort:
``````   def quick_sort(arr)
return arr if arr.length <= 1

pivot = arr.pop
left, right = arr.partition { |x| x < pivot }

quick_sort(left) + [pivot] + quick_sort(right)
end``````

You can test these sorting algorithms with sample input arrays to verify their correctness and efficiency. These implementations are basic and may not handle all edge cases or optimizations that you might find in production-ready libraries, but they serve as a good starting point for understanding how these algorithms work in practice.