2012年11月9日 星期五

排序

排序在電腦科學中是一個重要的部分,在這個問題中將限定使用一種排序方式,就是你只能交換相鄰的2個元素。將數列由小到大排序,並計算出最少要交換幾次才能排好。例如給你1 2 3,那需要交換的次數為0,因為已經排好了。例如給你2 3 1這個數列,第一次交換1跟3變成2 1 3,第二次交換2跟1變成1 2 3,因此最少需要交換2次才可排好。

輸入說明:輸入之奇數列為下一行數列中的個數,偶數列為數列資料,代表一組測試資料。每個數字與數字間的區隔為一個空白符號,當奇數列為0時表示結束。(請參照輸入範例)
輸入範圍:每個數列最少有2個數字,最多不超過100個。每個數列中的數字皆大於0,小於1000,且不重覆。
輸入範例:in.txt
3
1 2 3
3
2 3 1
0

輸出說明:對每一組輸入資料,輸出最少需要交換的次數。(請參照輸出範例)
輸出範例:out.txt
0
2

3 則留言:

  1. Dim mycount, num, temp, ans As Integer
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As 2
    Do
    Input #1, mycount
    If mycount = 0 Then Exit Do
    ReDim num(mycount)
    For i = 1 To mycount
    Input #1, num(i)
    Next
    For ii = 1 To mycount
    For iii = 1 To mycount - 1
    If num(iii) > num(iii + 1) Then
    temp = num(iii)
    num(iii) = num(iii + 1)
    ans = ans + 1
    End If
    Next
    Next
    Print #2, ans
    ans = 0

    Loop
    Close #2
    Close #1
    End
    End Sub

    回覆刪除
  2. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Do
    s = 0
    Input #1, n
    If n = 0 Then Exit Do
    Line Input #1, x
    a = Split(x)
    For i = 0 To UBound(a)
    For j = i + 1 To UBound(a)
    If a(i) > a(j) Then
    s = s + 1
    c = a(i)
    a(j) = a(i)
    a(i) = c
    End If
    Next
    Next
    Print #2, s
    Loop
    Close #1
    Close #2
    End
    End Sub

    回覆刪除
  3. Dim a()
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Do
    m = 0
    Input #1, s
    ReDim a(s)
    For i = 1 To s
    Input #1, a(i)
    Next
    If s <> 0 Then
    For i = 1 To s
    For j = 1 To s - 1
    If a(j) > a(j + 1) Then
    m = m + 1
    x = a(j)
    a(j) = a(j + 1)
    a(j + 1) = x
    End If
    Next
    Next
    Print #2, m
    ElseIf s = 0 Then: Exit Do
    End If
    Loop
    Close
    Close
    End
    End Sub

    回覆刪除