請設計一個程式,能在一個數列中,找出此數列第K大數字的位置。例如,有一個數列為8,20,27,17,13,28,35,31,第三大的數字為28,此數字的位置在串列中的第6個位置;第5大的數字為20,此數字的位置在串列中的第2個位置。
輸入說明:輸入之第一列為下一列數列中的個數。第二列為數列資料。每個數字與數字間的區隔為一個空白符號。第三列及以後的資料為要尋找第K大數字的K值,當為0時表示結束。(請參照輸入範例)
輸入範圍:輸入的數列最少為2個,最多不超過100個。每個數列中的數字皆大於0,小於1000,且不重覆。
輸入範例:in.txt
8
8 20 27 17 13 28 35 31
3
5
10
0
輸出說明:輸入的每個K值皆有一個位置的輸出結果,若超過數列的個數則輸出-1。(請參照輸出範例)
輸出範例:out.txt
6
2
-1
Dim mycount, num(), oknum(), temp, findnum As Integer
回覆刪除Dim havedo As Boolean
Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As 2
Input #1, mycount
ReDim num(mycount)
ReDim oknum(mycount)
For i = 1 To mycount
Input #1, num(i)
oknum(i) = num(i)
Next
For ii = 1 To mycount
For iii = ii + 1 To mycount
If oknum(ii) < oknum(iii) Then
temp = oknum(ii)
oknum(ii) = oknum(iii)
oknum(iii) = temp
End If
Next
Next
Do
Input #1, findnum
If findnum = 0 Then Exit Do
If findnum > mycount Then Print #2, "-1": Exit Do
For ai = 1 To mycount
If num(ai) = oknum(findnum) Then Print #2, ai: Exit For
Next
Loop
Close #2
Close #1
End
End Sub
哈囉
回覆刪除程式有小錯,看清楚題目,並不是"-1"時結束。
Dim mycount, num(), oknum(), temp, findnum As Integer
回覆刪除Dim havedo As Boolean
Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As 2
Input #1, mycount
ReDim num(mycount)
ReDim oknum(mycount)
For i = 1 To mycount
Input #1, num(i)
oknum(i) = num(i)
Next
For ii = 1 To mycount
For iii = ii + 1 To mycount
If oknum(ii) < oknum(iii) Then
temp = oknum(ii)
oknum(ii) = oknum(iii)
oknum(iii) = temp
End If
Next
Next
Do
Input #1, findnum
If findnum = 0 Then Exit Do
If findnum > mycount Then Print #2, "-1"
If Not findnum > mycount Then
For ai = 1 To mycount
If num(ai) = oknum(findnum) Then Print #2, ai: Exit For
Next
End If
Loop
Close #2
Close #1
End
End Sub
Dim a(), z()
回覆刪除Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, n
ReDim a(n), z(n)
For i = 1 To n
Input #1, a(i)
z(i) = a(i)
Next
For i = 1 To n
For j = 1 To n - 1
If a(j) < a(j + 1) Then
x = a(j)
a(j) = a(j + 1)
a(j + 1) = x
End If
Next
Next
'For i = 1 To n
' Print #2, a(i)
'Next
Do
Input #1, s
If s = 0 Then Exit Do
If s > n Then
Print #2, "-1"
Else
For m = 1 To n
If a(s) = z(m) Then Print #2, m: Exit For
Next
End If
Loop
Close
Close
End
End Sub