code.club

 找回密碼
 立即註冊
搜索
查看: 7528|回復: 6
打印 上一主題 下一主題

C語言冒泡排序法例子《轉》

[複製鏈接]
樓主
發表於 2014-12-17 18:01:51 | 顯示全部樓層
有個疑問,應是邏輯上的問題我一直百思不得其解

# include "stdio.h"
main(){
int i,j,a[5],temp;
for(i=0;i<5;i++)
scanf("%d,",&a);
for(i=0;i<5;i++)
for(j=i+1;j<5;j++)
if(a>a[j])
{temp=a;
a=a[j];
a[j]=temp;}
for(i=0;i<5;i++)
printf("%d",a);
printf("\n");
}

就是紅字的部份如果改成 j=1,結果就不正確了,但邏輯上 i=0而j=i+1 ,事實上也就是j=1啊? 因為i從0開始,j=i+1也等於是J 從 1算起,不是嗎?但顯然求得的答案是錯的。不知以上的邏輯錯在哪裡呢?
回復 支持 反對

使用道具 舉報

沙發
發表於 2014-12-25 18:17:43 | 顯示全部樓層
# include "stdio.h"
main(){
int i,j,a[5],temp;
for(i=0;i<5;i++)
scanf("%d,",&a);
for(i=0;i<5;i++)
for(j=i+1;j<5;j++)//這裡如果改成 (j=0;)則排序結果竟然就倒過來了?邏輯上沒有問題啊?怎會這樣?
if(a>a[j])
{temp=a;
a=a[j];
a[j]=temp;}
for(i=0;i<5;i++)
printf("%d",a);
printf("\n");
}
回復 支持 反對

使用道具 舉報

板凳
發表於 2014-12-25 18:42:59 | 顯示全部樓層
enter 發表於 2014-12-25 18:17
# include "stdio.h"
main(){
int i,j,a[5],temp;

邏輯上果然有錯,因為在x[0]這一輪時,假設x[0]>x[1]因而把值調換過來,此時x[0]<x[1]。然後到第二輪x[1]時,再拿 x[1]又去比一次 x[0](因為y一直都是從0開始),結果x[1]的值一定大於x[0](因為上一輪才調換過),所以等於又把大的值換給x[0]了。然後一路換下去,就等於最大的排最前面,和原來的本意相反了。
回復 支持 反對

使用道具 舉報

地板
發表於 2015-8-5 00:07:26 | 顯示全部樓層
這種兩兩相鄰互換的才叫冒泡排序法。

#include <iostream>
using namespace std;

int main(void){

int a[10]={23,10,6,89,302,74,100,8,383,44};
int x,y,temp;

for(x=1;x<=10;x++)
for(y=1;y<10;y++)
  if(a[y-1]>a[y]){
          temp=a[y-1];
          a[y-1]=a[y];
          a[y]=temp;
  }
  
  for(x=0;x<10;x++)
   cout<<a[x]<<" ";
   
   return 0;
}

而下面那種先用第一個一直往後比的方法選擇排序法。

#include <iostream>
    using namespace std;

    int main() {
        int n, a[1000]; // 一共n个数,n不超过1000。a用来保存这些数
        cin >> n;  
        // 输入n个数  
        for (int i = 0; i < n; i++) {
          cin >> a[i];
    }  
    // 冒泡,不断比较相邻的两个数,如果顺序错了,那么就交换
    for (int i = 0; i < n - 1; i++) {
      for (int j = 1; j < n - i; j++) {      
        if (a[j - 1] > a[j]) {
          int temp = a[j];
          a[j] = a[j - 1];
          a[j - 1] = temp;
        }   
      }  
    }  
    // 依次输出
   for (int i = 0; i < n; i++) {
     cout << a[i] << endl;  
   }  
   return 0;
}
回復 支持 反對

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|手機版|Archiver|code.club  

GMT+8, 2024-5-3 16:43 , Processed in 0.095495 second(s), 17 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表