1

今日からpythonの勉強を始めました。これは私の最初の本格的なプログラミング言語です...バブルソートを実行しようとしましたが、常に失敗します。どうしてか分かりません...

#!/usr/bin/python3.2
import random;

i = 0
x = 100
test = []

def createRandom():
        global i
        global test
        while i <= x:
                test.extend([random.randrange(1,100)]);
                i=i+1;
        return test;

def bubblesort():
        sorted=False;
        while sorted!=True:
                y = 0;
                l = len(test)-1
                print(l);
                while y < l:
                        sorted=True;
                        if test[y]<test[y+1]:
                                tmp = test[y]
                                test[y]=test[y+1];
                                test[y+1]=tmp;
                                y=y+1;
                                sorted=False;


createRandom();
bubblesort();
print(test);

エラー:

    root@Debian:~/python3# ./bubblesort.py
100
^CTraceback (most recent call last):
  File "./bubblesort.py", line 34, in <module>
    bubblesort();
  File "./bubblesort.py", line 25, in bubblesort
    if test[y]<test[y+1]:
KeyboardInterrupt

ご協力いただきありがとうございます!

4

4 に答える 4

0

これは、bubbleSort を完了するためのより良いアプローチではありませんか。

def bubbleSort(L):

        for i in range(len(L)-1,0,-1):
                範囲 (i) の j の場合:
                        L[j]>L[j+1]の場合:
                                温度=L[j]
                                L[j]=L[j+1]
                                L[j+1]=温度

        印刷 L
    print "List Sorted . END!!"
L=[4,5,6,7,2,3,8,7,9,6,7]
バブルソート(L)

このアプローチは、数千の要素まで有効です。1M のようなビンビン数を探している場合、このアプローチでは結果を証明するのに時間がかかります。他のアプローチに行き、私にも知らせてください;)

于 2016-04-07T11:26:16.113 に答える
0
 while y < l:
    sorted=True;
    if test[y]<test[y+1]:
        tmp = test[y]
        test[y]=test[y+1];
        test[y+1]=tmp;
        y=y+1;
        sorted=False;

y=y+1IF ステートメントが true の場合にのみ行います。

y=y+1ifの外に置いてみてください。うまくいくはずです。

于 2013-10-28T12:24:34.923 に答える
0

行う必要がある 2 つの変更があります。

tobias が言ったように、sorted=True を内側の while ループの外に移動します。そして、y = y + 1 を if ステートメントの外に移動する必要があります。

#!/usr/bin/python3.2
import random;

i = 0
x = 100
test = []

def createRandom():
        global i
        global test
        while i <= x:
                test.extend([random.randrange(1,100)]);
                i=i+1;
        return test;

def bubblesort():
        sorted=False;
        while sorted!=True:
                y = 0;
                l = len(test)-1
                print(l);
                sorted=True;
                while y < l:
                        if test[y]<test[y+1]:
                                tmp = test[y]
                                test[y]=test[y+1];
                                test[y+1]=tmp;
                                sorted=False;
                        y=y+1;


createRandom();
bubblesort();
print(t)
于 2013-10-28T12:24:52.143 に答える