用户输入一个阵列内交换 [英] Swapping within an Array of user inputs
问题描述
我在这里得到关于如何继续我的计划了一些建议。这是一个家庭作业和想法是呼吁另一种方法 INT已排序(int数组[],INT长度);
有了这些pre和后置条件。
- precondition:数组将是长度长整型数组。
- 后置条件:如果数组是排序(非减)命令,否则为false返回true 。
到目前为止,我已经能够放在一起用户输入数组多久也是应该的。
的#include<&stdio.h中GT;
#包括LT&;&math.h中GT;INT已排序(int数组[],INT lenght);INT已排序(int数组[],INT lenght)
{
INT交换;
诠释最小;
INT索引= 0;
scanf函数(%d个,&安培; lenght); INT列表[lenght]
INT I;
对于(i = 0; I< lenght;我++)
{
scanf函数(%d个,&安培;名单[I]);
} 返回0;
}诠释的main()
{}
我怎么会去要求用户输入给定的数组内的一次交换两个要素是什么?
最终产品应该类似于此:
运行示例:粗体用户输入
4 < - 长度,数组应
。
1 1 1 2 < - 用户输入这些4个号码
。
什么是下一步交换? 2 3
埃文排序的数组。
什么是下一步交换? 2 0
什么是下一步交换? 0 3
埃文排序的数组。
什么是下一步交换? -1 -1
史蒂夫是正确的!
-1 -1结束交换处理,并检查数组进行排序。
块引用>解决方案而(I = -1&安培;!&安培;!J = -1){
scanf函数(%D,与功放I,功放; j)条;
掉期(安培;阵列[我],和放大器;阵列[J]);
}和
掉期()
是这样的:无效掉期(INT *一,为int * B){
INT C = *一个;
* A = * B;
* B = C;
}有可能是为swaping两个变量做一些按位异或,我不记得了一个漂亮的把戏。
I am here to get some advice on how to continue my program. It is a homework assignment and the idea is to have another method called
int is_sorted(int array[], int length);
With these pre and post conditions.
- Precondition: array will be an array of integers of length length.
- Postcondition: returns true if the array is in sorted(nondecreasing) order, or false otherwise.
So far I have been able to put together the user input array and how long it should be.
#include <stdio.h> #include <math.h> int is_sorted(int array[], int lenght); int is_sorted(int array[], int lenght) { int swap; int smallest; int index = 0; scanf("%d", &lenght); int list[lenght]; int i; for (i = 0; i < lenght; i++) { scanf("%d", &list[i]); } return 0; } int main() { }
How would I go about asking for a user input to swap two elements at a time within the given array?
The final product should look similar to this:
Sample Run: User input in bold
4 <- The length that the array should be.
1 1 1 2 <- user input these 4 numbers.
WHAT IS THE NEXT SWAP? 2 3
EVAN HAS UNSORTED THE ARRAY.
WHAT IS THE NEXT SWAP? 2 0
WHAT IS THE NEXT SWAP? 0 3
EVAN HAS SORTED THE ARRAY.
WHAT IS THE NEXT SWAP? -1 -1
STEVE WAS RIGHT!
-1 -1 end the swapping process and check if the array is sorted.
解决方案while(i != -1 && j != -1){ scanf("%d %d", &i, &j); swap(&array[i], &array[j]); }
and
swap()
looks like this:void swap(int* a, int* b){ int c = *a; *a = *b; *b = c; }
There's probably a nifty trick for swaping two variables doing some bitwise xor-ing that I don't remember about.
这篇关于用户输入一个阵列内交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!