python实现的各种排序算法代码
代码如下:
# -*- coding: utf-8 -*-
# 测试各种排序算法
# link:www.bitsCN.com
# date:2013/2/2
#选择排序
def select_sort(sort_array):
for i, elem in enumerate(sort_array):
for j, elem in enumerate(sort_array[i:]):
if sort_array[i] > sort_array[j + i]:
#交换
sort_array[i], sort_array[j + i] = sort_array[j + i], sort_array[i]
#冒泡排序
def bubble_sort(sort_array):
for i, elem in enumerate(sort_array):
for j, elem in enumerate(sort_array[:len(sort_array) - i - 1]):
if sort_array[j] > sort_array[j + 1]:
sort_array[j], sort_array[j + 1] = sort_array[j + 1], sort_array[j]
#插入排序
def insert_sort(sort_array):
for i, elem in enumerate(sort_array):
for j, elem in enumerate(sort_array[:i]):
if sort_array[j] > sort_array[i]:
sort_array.insert(j, sort_array[i])
del sort_array[i + 1]
#归并排序
def merge_sort_wrapper(sort_array):
merge_sort(sort_array, 0, len(sort_array) - 1)
def merge_sort(sort_array, left = 0, right = 0):
if left center = (left + right) / 2
merge_sort(sort_array, left, center)
merge_sort(sort_array, center + 1, right)
merge(sort_array, left, right, center)
def merge(sort_array, left, right, center):
result = []
arrayA = sort_array[left:center + 1]
arrayB = sort_array[center + 1:right + 1]
while((len(arrayA) > 0) and (len(arrayB) > 0)):
if(arrayA[0] > arrayB[0]):
result.append(arrayB.pop(0))
else:
result.append(arrayA.pop(0))
if(len(arrayA) > 0):
result.extend(arrayA)
if(len(arrayB) > 0):
result.extend(arrayB)
sort_array[left:right + 1] = result
#快排
def quick_sort(sort_array):
if(len(sort_array) return
left = [x for x in sort_array[1:] if x right = [x for x in sort_array[1:] if x >= sort_array[0]]
quick_sort(left)
quick_sort(right)
sort_array[:] = left + [sort_array[0]] + right
#shell排序
def shell_sort(sort_array):
dist=len(sort_array)/2
while dist > 0:
for i in range(dist,len(sort_array)):
tmp=sort_array[i]
j = i
while j >= dist and tmp sort_array[j] = sort_array[j - dist]
j -= dist
sort_array[j] = tmp
dist /= 2
#基数排序,均为整数,不支持负数和重复
def radix_sort(sort_array):
max_elem = max(sort_array)
bucket_list = []
for i in range(max_elem):
bucket_list.insert(i, 0)
for x in sort_array:
bucket_list[x - 1] = -1
sort_array[:] = [x + 1 for x in range(len(bucket_list)) if bucket_list[x] == -1]
#堆排序
def heap_sort(sort_array):
#没有写出来,再想想
pass
#测试例子
def algo_sort_test(sort_array, sort_method):
sort_method(sort_array)
if __name__ == '__main__':
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
algo_sort_test(sort_array, select_sort)
print sort_array
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
algo_sort_test(sort_array, bubble_sort)
print sort_array
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
algo_sort_test(sort_array, insert_sort)
print sort_array
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
algo_sort_test(sort_array, merge_sort_wrapper)
print sort_array
sort_array = [1, 2, 3, 5, -4, 4, 10, 300, 19, 13, 16, 18, 500, 190, 456, 23]
algo_sort_test(sort_array, quick_sort)
print sort_array
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
algo_sort_test(sort_array, shell_sort)
print sort_array
sort_array = [1, 2, 3, 5, 4, 10, 19, 13, 16, 18, 190, 456, 23]
algo_sort_test(sort_array, radix_sort)
print sort_array
print 'OK'
非常基础的知识内容,选择、冒泡、插入、归并、基数,还有快排都能手写出来,但写了一遍发现堆排序忘了怎么做了。要复习啦。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

1. Background of the problem 1. Introduction to the two-sided market experiment The two-sided market, that is, a platform, includes two participants, producers and consumers, and both parties promote each other. For example, Kuaishou has a video producer and a video consumer, and the two identities may overlap to a certain extent. Bilateral experiment is an experimental method that combines groups on the producer and consumer sides. Bilateral experiments have the following advantages: (1) The impact of the new strategy on two aspects can be detected simultaneously, such as changes in product DAU and the number of people uploading works. Bilateral platforms often have cross-side network effects. The more readers there are, the more active the authors will be, and the more active the authors will be, the more readers will follow. (2) Effect overflow and transfer can be detected. (3) Help us better understand the mechanism of action. The AB experiment itself cannot tell us the relationship between cause and effect, only

How to filter and sort data in Vue technology development In Vue technology development, data filtering and sorting are very common and important functions. Through data filtering and sorting, we can quickly query and display the information we need, improving user experience. This article will introduce how to filter and sort data in Vue, and provide specific code examples to help readers better understand and use these functions. 1. Data filtering Data filtering refers to filtering out data that meets the requirements based on specific conditions. In Vue, we can pass comp

Organizing | Nuka-Cola, Chu Xingjuan Friends who have taken basic computer science courses must have personally designed a sorting algorithm - that is, using code to rearrange the items in an unordered list in ascending or descending order. It's an interesting challenge, and there are many possible ways to do it. A lot of time has been invested in figuring out how to accomplish sorting tasks more efficiently. As a basic operation, sorting algorithms are built into the standard libraries of most programming languages. There are many different sorting techniques and algorithms used in code bases around the world to organize large amounts of data online, but at least as far as the C++ libraries used with the LLVM compiler are concerned, the sorting code has not changed in more than a decade. Recently, the Google DeepMindAI team has now developed a

How to use the radix sort algorithm in C++ The radix sort algorithm is a non-comparative sorting algorithm that completes sorting by dividing the elements to be sorted into a limited set of digits. In C++, we can use the radix sort algorithm to sort a set of integers. Below we will discuss in detail how to implement the radix sort algorithm, with specific code examples. Algorithm idea The idea of the radix sorting algorithm is to divide the elements to be sorted into a limited set of digital bits, and then sort the elements on each bit in turn. Sorting on each bit is completed

How to implement the selection sort algorithm in C# Selection sort (SelectionSort) is a simple and intuitive sorting algorithm. Its basic idea is to select the smallest (or largest) element from the elements to be sorted each time and put it at the end of the sorted sequence. Repeat this process until all elements are sorted. Let's learn more about how to implement the selection sort algorithm in C#, along with specific code examples. Creating a selection sort method First, we need to create a method for implementing selection sort. This method accepts a

Swoole is a high-performance network communication framework based on PHP language. It supports the implementation of multiple asynchronous IO modes and multiple advanced network protocols. On the basis of Swoole, we can use its multi-threading function to implement efficient algorithm operations, such as high-speed sorting algorithms. The high-speed sorting algorithm (QuickSort) is a common sorting algorithm. By locating a benchmark element, the elements are divided into two subsequences. Those smaller than the benchmark element are placed on the left, and those greater than or equal to the benchmark element are placed on the right. Then the left and right subsequences are placed. subsequence recursion

For different scenarios, it is crucial to choose the appropriate PHP array sorting algorithm. Bubble sort is suitable for small-scale arrays without stability requirements; quick sort has the lowest time complexity in most cases; merge sort has high stability and is suitable for scenarios that require stable results; selection sort is suitable for situations without stability requirements. Situation; Heap sort efficiently finds the maximum or minimum value. Through comparison of actual cases, quick sort is superior to other algorithms in terms of time efficiency, but merge sort should be chosen when stability needs to be considered.

Array sorting algorithms are used to arrange elements in a specific order. Common types of algorithms include: Bubble sort: swap positions by comparing adjacent elements. Selection sort: Find the smallest element and swap it to the current position. Insertion sort: Insert elements one by one to the correct position. Quick sort: divide and conquer method, select the pivot element to divide the array. Merge Sort: Divide and Conquer, Recursive Sorting and Merging Subarrays.
