[英]Bubble Sort using Bubble Up
給定冒泡排序的算法:
Algorithm BubbleSort(A[0...n]):
for i <- 0 to n-2 do
for j <- 0 to n-2-i do
if(A[j+1] < A[j] then swap(A[j], A[j+1]))
我必須使用我們將最小元素“冒泡”到列表中第ith個位置的第i個位置來重寫Bubble Sort算法。
誰能幫我這個?
#include<stdio.h>
void bubbleSort(int *x,int size)
{
int e,f,m,g;
m=size-2;
while(m>0)
{
e=0;
f=1;
while(e<=m)
{
if(x[f]<x[e])
{
g=x[e]; //swaping
x[e]=x[f];
x[f]=g;
}
e++;
f++;
}
m--;
}
}
void main()
{
int x[10],y;
for(y=0;y<=9;y++) //loop to insert 10 numbers into an array
{
printf("Enter a number: ");
scanf("%d",&x[y]);
}
bubbleSort(x,10); //pass number entered by user and size of array to bubbleSort
for(y=0;y<=9;y++) //loop to print sorted numbers
{
printf("%d\n",x[y]);
}
}
當前,您是從頭開始遍歷數組,因此,如果遇到最大的元素,它將“冒泡”到數組的末尾。 如果要進行相反的操作,即將最小的元素“冒泡”到起點,則需要從終點到起點以相反的方向遍歷數組。 希望它能幫助您找到方法。
看來答案還沒有被接受。 因此,嘗試檢查這是否仍然是一個問題。
我認為這可能是Java中可能的實現。 正如@Warlord所提到的,該算法是要確保將要排序的數組想象為一個垂直數組。 每次通過時,我們要做的就是檢查下面是否有較大的元素,以及是否發現該元素冒泡到頂部。
static void bubbleUpSort(int[] arr){
final int N = arr.length;
int tmp = 0;
for (int i=0; i < N; i++){
for (int j=N-1; j >= i+1; j--){
if (arr[j] < arr[j-1]){
tmp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = tmp;
}
}
}
for (int k =0; k < arr.length; k++){
System.out.print(arr[k] + " ");
}
}
從main調用為:
public static void main(String[] args) {
System.out.println("Bubble Up Sort");
int[] bUp = {19, 2, 9, 4, 7, 12, 13, 3, 6};
bubbleUpSort(bUp);
}
將每個與鄰居進行比較,如果第一個大於下一個,則交換
function bubbleSort(arr){
let temp;
console.log("Input Array");
console.log(arr);
for (let i = 0; i < arr.length-1; i++) {
for (let j = 0; j < arr.length-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
console.log(arr[j],"swapped with",arr[j+1])
console.log(arr);
} else {
console.log("SKIP");
}
}
}
console.log("Sorted using Bubble Sort");
return arr;
}
console.log(bubbleSort([7,6,9,8,2,1,4,3,5]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.