gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
写一个java冒泡排序
- User
写一个java冒泡排序
- Assistant
下面是一个使用Java实现的冒泡排序算法的示例:
public class BubbleSort { public static void main(String[] args) { int[] array = {5, 3, 8, 6, 4}; System.out.println("排序前:"); printArray(array); bubbleSort(array); System.out.println("\n排序后:"); printArray(array); } public static void bubbleSort(int[] array) { int n = array.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - 1 - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } public static void printArray(int[] array) { for (int num : array) { System.out.print(num + " "); } } }此示例中,我们定义了一个
bubbleSort方法来执行冒泡排序。在每一轮排序中,我们比较相邻的两个元素,如果顺序不正确,则交换它们。重复进行这个过程,直到整个数组按照升序排列。最后,我们使用printArray方法打印排序后的数组。运行此代码,您将得到以下输出:排序前: 5 3 8 6 4 排序后: 3 4 5 6 8