我在C中使用数组搜索冒泡排序,stackoverflow为我提供了以下代码,这对降序数字不起作用(1,2,3,4,.....)
#include<stdio.h>
int main()
{
int numArray[5],temp,j;
printf("Please enter five integers:\n");
printf("First Number\n");
scanf("%d", &numArray[0]);
printf("Second Number\n");
scanf("%d", &numArray[1]);
printf("Third Number\n");
scanf("%d", &numArray[2]);
printf("Fourth Number\n");
scanf("%d", &numArray[3]);
printf("Fifth Number\n");
scanf("%d", &numArray[4]);
for (j=0; j<=5; ++j) {
if (numArray[j] > numArray[j+1]) {
temp = numArray[j];
numArray[j] = numArray[j+1];
numArray[j+1] = temp;
}
}
for(int j = 0; j < 5; j++) {
printf("%d ", numArray[j]);
}
return 0;
}
更新 谢谢你,使用另一个for循环,我做了我的升序数字冒泡排序代码
int main()
{
int ara[5]={12,16,14,11,10};
int i,j,temp;
for(i=0;i<5;i++)
{
for(j=0;j<=5;j++)
{
if(ara[j]>ara[j+1])
{
temp=ara[j];
ara[j]=ara[j+1];
ara[j+1]=temp;
}
}
}
for(j=0;j<5;j++)
printf("%d\n",ara[j]);
}
答案 0 :(得分:0)
试试这个:
for (i=0; i<5; i++) {
for (j=0; j<5; j++) {
if (numArray[i] > numArray[j]) {
temp = numArray[j];
numArray[j] = numArray[i];
numArray[i] = temp;
}
}
}
答案 1 :(得分:0)
您将数组初始化为长度为5 int numArray[5]
因此,您只能使用索引0,1,2,3,4
。
因此,你的循环for (j=0; j<=5; ++j)
将产生一个不存在的索引5
。
答案 2 :(得分:0)
请参考下面给出的代码,我已经为您的代码添加了逻辑,现在工作正常
#include <stdio.h>
int main()
{
int numArray[5],temp,j;
printf("Please enter five integers:\n");
printf("First Number\n");
scanf("%d", &numArray[0]);
printf("Second Number\n");
scanf("%d", &numArray[1]);
printf("Third Number\n");
scanf("%d", &numArray[2]);
printf("Fourth Number\n");
scanf("%d", &numArray[3]);
printf("Fifth Number\n");
scanf("%d", &numArray[4]);
int len = sizeof(numArray)/sizeof(numArray[0]);
printf("len of array %d \n", len);
int i=0;
for(i = 0;i<len;i++)
{
for (j=0; j<len-i-1; j++) {
if (numArray[j] > numArray[j+1]) {
temp = numArray[j];
numArray[j] = numArray[j+1];
numArray[j+1] = temp;
}
}
}
for(j = 0; j < 5; j++) {
printf("%d ", numArray[j]);
}
return 0;
}
答案 3 :(得分:0)
int swaped = 1;
while(swaped){
swaped =0;
for (j=0; j<5-1,; ++j) {//-1 for (j+1) upper bound is 4
//descending order : When the order of reverse exchange
if (numArray[j] < numArray[j+1]) {
temp = numArray[j];
numArray[j] = numArray[j+1];
numArray[j+1] = temp;
swaped = 1;
}
}
}
答案 4 :(得分:0)
我认为更有效的方法是,
for (i=0; i<4; i++) {
for (j=i+1; j<5; j++) {
if (numArray[i] > numArray[j]) {
temp = numArray[j];
numArray[j] = numArray[i];
numArray[i] = temp;
}
}
}