对整数列进行升序和降序排序可以使用不同的算法和编程语言来实现。以下是两种常见的排序算法和对应的示例代码:
示例代码(Python):
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
# 测试
arr = [64, 34, 25, 12, 22, 11, 90]
ascending_order = bubble_sort(arr)
descending_order = bubble_sort(arr)[::-1]
print("升序排序结果:", ascending_order)
print("降序排序结果:", descending_order)
示例代码(Java):
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
public static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
quickSort(arr, 0, arr.length - 1);
System.out.print("升序排序结果:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
System.out.print("降序排序结果:");
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}
以上示例代码分别使用了冒泡排序和快速排序对整数列进行升序和降序排序。在实际开发中,可以根据具体需求和数据规模选择合适的排序算法。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云