我對 C 甚至編碼都很陌生。我試圖制作一個簡單的陣列排序器,我首先輸入將在陣列中的元素數量,然后輸入元素。我的結果應該是按升序排序的陣列。如果插入的元素相同,我沒有考慮過這種情況。所以我很想從你們那里得到一些幫助。我面臨的主要錯誤是只有第一個未排序的元素被排序,而其余元素要么互換要么保持不變。
int main(){
int x;
cout<<"Enter no. of elements"<<endl;
cin>>x;
int A[x];
for (int i = 0;i<x;i ){
cin>>A[i];
}
for(int i=0;i<x;i )
cout<<A[i]<<",";
int count=0;
if(count <= (x-1)){
for (int i=0;i<(x-1);i ){
if(A[i]>A[i 1]){
int a;
a = A[i];
A[i] = A[(i 1)];
A[i 1] = a;
}
else if(A[i]<A[i 1])
count ;
}
}
cout<<"Sorted array:";
for(int i=0;i<x;i )
cout<<A[i]<<",";
return 0;
}
uj5u.com熱心網友回復:
您宣告了一個可變長度陣列
int x;
cout<<"Enter no. of elements"<<endl;
cin>>x;
int A[x];
因為它的大小不是編譯時常量。
然而,可變長度陣列不是標準的 C 特性,盡管一些編譯器有自己的語言擴展來支持可變長度陣列,
最好使用類模板std::vector。
另一個問題是您似乎正在嘗試使用冒泡排序方法對陣列進行排序。但是這種方法需要兩個回圈。
這是一個演示程式,展示了如何實作冒泡排序演算法。
#include <iostream>
int main()
{
int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
const size_t N = sizeof( a ) / sizeof( *a );
for (const auto &item : a)
{
std::cout << item << ' ';
}
std::cout << '\n';
for (size_t last = N, sorted = N; not ( last < 2 ); last = sorted)
{
for (size_t i = sorted = 1; i < last; i )
{
if (a[i] < a[i - 1])
{
// std::swap( a[i-1], a[i] );
int tmp = a[i - 1];
a[i - 1] = a[i];
a[i] = tmp;
sorted = i;
}
}
}
for (const auto &item : a)
{
std::cout << item << ' ';
}
std::cout << '\n';
}
程式輸出為
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
uj5u.com熱心網友回復:
讓我們嘗試以下方法:
通過與最后一個元素交換,找到陣列中最大的元素并將其移動到末尾;
重復陣列,但最后一個元素,依此類推。
要找到 中的最大元素A[0..m-1],請掃描陣列并保留迄今為止最大的索引,讓l. 該索引可以初始化為0。
// Move the largest to the end
int l= 0;
for (int i= 1; i < m; i )
{
if (A[i] > A[l]) l= i;
}
// A[l] is the largest in A[0..m-1]
Swap(A[l], A[m-1]);
// A[m-1] is the largest in A[0..m-1]
要排序,請重復遞減m。當子陣列只包含一個元素時,您可以停止:
// Sort
for (int m= n-1; m > 1; m--)
{
// Move the largest to the end
....
}
撰寫Swap操作和組裝整個代碼是您的任務。還要檢查
Move極限情況下的正確性m= 0, 1, 2。Sort極限情況下的正確性n= 1, 2, 3。您如何檢測代碼以驗證
Move其作業是否正常。您如何檢測代碼以驗證
Sort其作業是否正常。在相等鍵的情況下會發生什么。
uj5u.com熱心網友回復:
您的代碼可以稍作修復以使其正常作業。
只需替換if (count <= (x - 1))為while (count < (x - 1))并count = 0;在回圈開始時設定,再加上替換else if (A[i] < A[i 1])為else。你的代碼開始作業了!
我在下面的代碼中進行了必要的修復。我還進行了格式化(縮進和空格)以使代碼看起來更好。休息保持不變。
如我所見,您有一種冒泡排序。
在線嘗試!
#include <iostream>
using namespace std;
int main() {
int x;
cout << "Enter no. of elements" << endl;
cin >> x;
int A[x];
for (int i = 0; i < x; i ) {
cin >> A[i];
}
for (int i = 0; i < x; i )
cout << A[i] << ",";
int count = 0;
while (count < (x - 1)) {
count = 0;
for (int i = 0; i < (x - 1); i ) {
if (A[i] > A[i 1]) {
int a;
a = A[i];
A[i] = A[(i 1)];
A[i 1] = a;
} else
count ;
}
}
cout << "Sorted array:";
for (int i = 0; i < x; i )
cout << A[i] << ",";
return 0;
}
輸入:
10
7 3 5 9 1 8 6 0 2 4
輸出:
7,3,5,9,1,8,6,0,2,4,Sorted array:0,1,2,3,4,5,6,7,8,9,
uj5u.com熱心網友回復:
如果您將陣列的大小作為用戶的輸入,則必須在 c 中動態創建陣列,例如 int *array=new int(x) 并且在獲取元素的輸入后,只需運行從 0 到 size 的嵌套回圈,然后從 0 到 size-1 的內部回圈并檢查 if(A[i]>A[i 1]) 如果為真,則交換值,否則繼續
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513846.html
標籤:C 数组算法排序冒泡排序
