一个整型数组,包含负数和正数,实现一个函数,把所有的负数挪到数组的左边,所有的正数挪到数组的右边。
思路:使用两个指针,分别从数组的两头遍历数组,从左边找到一个负数,从右边找到一个正数,交换这两个数字,循环此过程,直到两个指针相遇。
C++
.h文件
#ifndef PositiveNegative_h
#define PositiveNegative_h
#include <stdio.h>
#endif /* PositiveNegative_h */
/*
arr为数组,low为数组最小的序号,high为最大的序号
*/
void movePositiveNegative(int arr[], int low, int high);
.cpp文件
#include "PositiveNegative.h"
void movePositiveNegative(int arr[], int low, int high){
if (arr == NULL || low > high) {
return;
}
while (low < high) {
//从左边找到第一个正数
while (low < high && arr[low] < 0) {
low++;
}
//从右边找到第一个负数
while (low < high && arr[high] > 0) {
high--;
}
int tmp = arr[low];
arr[low] = arr[high];
arr[high] = tmp;
}
}
main函数
#include <iostream>
#include "PositiveNegative.h"
int main(int argc, const char * argv[]) {
int arr[8] = {1,2,-1,-2,-3,5,6,4};
movePositiveNegative(arr, 0, 7);
for (int i = 0; i < 8; i++) {
std::cout<<arr[i]<<std::endl;
}
return 0;
}