C 语言中数组平移
数组平移是指将数组中的元素集体向左或向右移动一定的位置。C 语言中实现数组平移有两种常见方法:
方法 1:使用额外的临时数组
-
创建一个新的数组,其大小与原数组相同。
使用循环逐个复制原数组中从指定偏移量开始的元素到新数组中。
将新数组复制回原数组。
<code class="c">void array_shift_left(int arr[], int size, int offset) {
int temp[size];
for (int i = 0; i < size; i++) {
temp[i] = arr[(i + offset) % size];
}
memcpy(arr, temp, size * sizeof(int));
}</code>方法 2:使用循环平移
立即学习“C语言免费学习笔记(深入)”;
这种方法通过重复交换数组中的元素来实现平移。
-
获取要平移的距离。
使用两个嵌套循环:外层循环遍历要平移的元素,内层循环执行实际平移。
交换相邻元素,直到所有元素移动到正确的位置。
<code class="c">void array_shift_right(int arr[], int size, int offset) {
for (int i = 0; i < offset; i++) {
for (int j = size - 1; j > 0; j--) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}</code> 