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)
if __name__ == "__main__":
arr = [5, 9, 3, 1, 2, 8, 4, 7, 6]
print("原数组:", arr)
sorted_arr = quick_sort(arr)
print("排序后的数组:", sorted_arr)
Java实现的链表数据结构
public class LinkedList {
Node head; // 头结点
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
}
}
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = newNode;
}
}
public void display() {
Node currentNode = head;
while (currentNode != null) {
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
}
}
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.append(2);
linkedList.append(4);
linkedList.append(6);
linkedList.append(8);
System.out.println("链表元素:");
linkedList.display();
}
}
PHP实现的二分查找算法
function binary_search($arr, $target) {
$left = 0;
$right = count($arr) - 1;
while ($left<= $right) {
$mid = floor(($left + $right) / 2);
if ($arr[$mid] == $target) {
return $mid;
}
if ($arr[$mid] > $target) {
$right = $mid - 1;
} else {
$left = $mid + 1;
}
}
return -1; // 未找到目标元素
}
$arr = [1, 3, 5, 7, 9];
$target = 5;
$index = binary_search($arr, $target);
if ($index != -1) {
echo "目标元素 $target 的索引为 $index";
} else {
echo "未找到目标元素 $target";
}