Khác biệt giữa bản sửa đổi của “Sắp xếp nổi bọt”

Nội dung được xóa Nội dung được thêm vào
Không có tóm lược sửa đổi
Thẻ: Sửa đổi di động Sửa đổi từ trang di động
Thẻ: Sửa đổi di động Sửa đổi từ trang di động
Dòng 68:
=== Viết bằng Java ===
<source lang="java">
private static void bubbleSort(int[] unsortedArray, int length) {
int temp, counter, index;
for(counter=0; counter<length-1; counter++) { //Loop once for each element in the array.
for(index=0; index<length-1-counter; index++) { //Once for each element, minus the counter.
if(unsortedArray[index] > unsortedArray[index+1]) { //Test if need a swap or not.
temp = unsortedArray[index]; //These three lines just swap the two elements:
unsortedArray[index] = unsortedArray[index+1];
unsortedArray[index+1] = temp;
}
}
}
}
</source>
 
=== '''Viết bằng C++''' ===
#include<iostream>
using namespace std;
void nhap(int arr[], int &n) {
cout << "Nhap so phan tu cua mang n = ";
cin >> n;
for (int i = 0; i < n; i++) {
cout << "Phan tu arr["<<i<<"]" << " = ";
cin >> arr[i];
}
}
void bubblesort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// swap
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void inkq(int arr[], int &n) {
cout << "[ ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << "]" << endl;
}
int main () {
int arr[100], n;
nhap(arr, n);
cout << "=< Mang ban dau la: ";
inkq(arr, n);
bubblesort(arr, n);
cout<<"=> Mang khi sap xep la: ";
inkq(arr, n);
return 0;
}
 
 
 
=== '''Viết bằng PHP''' ===
<syntaxhighlight lang="php" line="1">
$myArr = [1, 1, 7, 6, 5, 4, 3, 2, 1, 3, 2, 1];
 
$count = count($myArr);
 
$t = 0;
 
for($i=0;$i<$count;$i++)
{
for($j=$count-1; $j > $i; $j--){
if($myArr[$j] < $myArr[$j-1])
{
$t = $myArr[$j];
$myArr[$j] = $myArr[$j-1];
$myArr[$j-1] = $t;
}
}
}
 
for($i=0;$i<$count;$i++){
echo $myArr[$i]." ";
}
</syntaxhighlight>
 
== Xem thêm ==