[英]Sorting array using pointers
我正在嘗試使用指針按降序對數組中的數字進行排序。 我現在所擁有的只是將數字再次打印出來而不進行排序。 如何獲得對數字進行排序的功能?
void new_sort(int nums[], int count) {
int round;
int i;
int inorder;
int temp;
int *num_ptr = nums;
inorder=0;
for (round = count -1; (round>0)&&(!inorder); round--) {
inorder=1;
for(i=0; i<round; i++) {
if (*num_ptr<*(num_ptr+1)) {
inorder = 0;
temp = *num_ptr;
*num_ptr = *(num_ptr+1);
*(num_ptr+1) = temp;
}
}
}
}
您只看過*num_ptr
和*(num_ptr+1)
。 您應該在移動時使用i
或“移動”指針。
正如John3136所指出的,您只會檢查第一個元素的蜂鳴聲少於下一個元素。 我以為你不想讓我有一個解決方案,使用指針去使用隨機數組索引。 我並沒有真正改變您的代碼,我只是使用指針而不是您使用的計數器。 我用一個數組對其進行了測試,我認為您代碼的其他部分工作正常!
void new_sort(int* const nums, int count) {
int* const end_ptr = nums + count;
int* round;
int inorder;
int temp;
inorder = 0;
int* num_ptr;
for (round = end_ptr - 1; round != nums && (!inorder); round--) {
inorder = 1;
for (num_ptr = nums; num_ptr != round; num_ptr++) {
if (*num_ptr < *(num_ptr + 1)) {
inorder = 0;
temp = *num_ptr;
*num_ptr = *(num_ptr + 1);
*(num_ptr + 1) = temp;
}
}
}
}
int main()
{
int nums[] = { 10, 4, 7, 5, 4, 3, 2, 7, 8, 9, 11, 23, 1 };
new_sort(nums, sizeof(nums) / sizeof(*nums));
return 0;
}
希望這會有所幫助。 干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.