[英]Bubble sort isn't working while sorting in ascending order
我創建了一個程序,它從用戶那里尋找關於 5 位數字(使用 char 數據類型)的輸入,並根據 if 語句中設置的參數,根據升序或降序對其進行冒泡排序。
案例 1:如果 (a[j] < a[j+1])
案例 2:如果 (a[j] > a[j+1])
下面是我的代碼:
int main()
{
char a[6];
int i, temp;
int j = 0;
printf("Enter a 5 digit number\n");
scanf("%s", a);
printf("You entered : %s\n", a);
for ( i = 0 ; i < 5 ; i++ )
{
for ( j = 0 ; j < 6 - 1 - i ; ++j )
{
if ( a[j] > a[j+1] )
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("Bubble Sorted number : %s\n", a);
return 0;
}
這個內部 for 循環
for ( j = 0 ; j < 6 - 1 - i ; ++j )
{
if ( a[j] > a[j+1] )
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
可以覆蓋存儲在數組a
中的字符串的終止零字符'\0'
。
當在外循環中變量i
等於0
那么你實際上有以下內循環
for ( j = 0 ; j < 5 ; ++j )
{
if ( a[j] > a[j+1] )
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
在這種情況下,當循環中的j
等於4
時,與a[5]
相同的表達式a[j+1]
將產生終止零字符,該字符將與存儲在數組元素a[4]
中的字符交換a[4]
。
像這樣重寫內部循環
for ( j = 1 ; j < 6 - 1 - i ; ++j )
{
if ( a[j-1] > a[j] )
{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.