1. 程式人生 > >用不同的方法將⼀個數組中的資料按相反的順序儲存

用不同的方法將⼀個數組中的資料按相反的順序儲存

將⼀個數組中的資料按相反的順序儲存;
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }
處理完成之後,陣列的內容變成{ 0, 9, 8, 7, 6, 5, 4, 3, 2, 1 }
//void reverse(int arr[], int sz)
//{
//int left = 0;
//int right = sz - 1;
//while (left < right)
//{
//int tmp = arr[left];
//arr[left] = arr[right];
//arr[right] = tmp;
//left++;
//right--;
//}
//}
//void reverse(char* arr, int sz)
//{
//int left = 0;
//int right = sz - 1;
//while (left < right)
//{
//int tmp = *(arr+left);
//*(arr + left) = *(arr+right);
//*(arr + right) = tmp;
//left++;
//right--;
//}
//}
void Reverse(int* left, int* right)
{
assert(left != NULL);
assert(right != NULL);
while (left < right)
{
int tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
int main()
{
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int sz = sizeof(a) / sizeof(a[0]);
//reverse(a, sz);
Reverse(a, a + sz - 1);
system("pause");
return 0;
}