代碼轉換成圖片
輸入
輸出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 function bubbleSort(arr) { let n = arr.length; let swapped; do { swapped = false; for (let i = 0; i < n - 1; i++) { if (arr[i] > arr[i + 1]) { // Swap the elements let temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; swapped = true; } } // Reduce n since the largest element will be at the end after each iteration n--; } while (swapped); return arr; } // Example usage let array = [64, 34, 25, 12, 22, 11, 90]; console.log("Sorted array:", bubbleSort(array));

Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 function bubbleSort(arr) { let n = arr.length; let swapped; do { swapped = false; for (let i = 0; i < n - 1; i++) { if (arr[i] > arr[i + 1]) { // Swap the elements let temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; swapped = true; } } // Reduce n since the largest element will be at the end after each iteration n--; } while (swapped); return arr; } // Example usage let array = [64, 34, 25, 12, 22, 11, 90]; console.log("Sorted array:", bubbleSort(array));

在 ChatGPT 中使用

請展示冒泡排序的代碼並轉換成圖片
AI
這是用 Python 編寫的冒泡排序代碼的圖片: 查看圖片.