topic
There is a non-zero integer array A[n], try to write an algorithm to put integers less than 0 in A before A, and integers greater than 0 after A, requiring no other auxiliary data structures!
analysis
We set two flags, i and j. i is the head element, j is a certain element! Let them traverse from both ends to the middle! When i>=j, the loop ends! Within this loop is divided into four branches selected is determined when a[i] > 0 && a[j] > 0
j is moved forward, I do not move; when a[i] > 0 && a[j] < 0
, the position of the two elements to be exchanged, and i ++, j-; when a[i] < 0 && a[j]>0
, the position of the two elements to be exchanged , And i++, j–; when a[i] < 0 && a[j] < 0
i++;
Code
void Rearrange(int a[], int n) {
int i = 0; //{-1,2,3,-5,0,1}
int j = 4; //{-1,-5,3}
int temp;
while (i < j) {
if (a[i] > 0 && a[j] > 0) {
j--;
}
else if (a[i] > 0 && a[j] < 0) {
temp = a[j];
a[j] = a[i];
a[i] = temp;
i++;
j--;
}
else if (a[i] < 0 && a[j]>0) {
temp = a[j];
a[j] = a[i];
a[i] = temp;
i++;
j--;
}
else if (a[i] < 0 && a[j] < 0) {
i++;
}
}
}
test
// ConsoleApplication6.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
void Rearrange(int a[], int n) {
int i = 0; //{-1,2,3,-5,0,1}
int j = 4; //{-1,-5,3}
int temp;
while (i < j) {
if (a[i] > 0 && a[j] > 0) {
j--;
}
else if (a[i] > 0 && a[j] < 0) {
temp = a[j];
a[j] = a[i];
a[i] = temp;
i++;
j--;
}
else if (a[i] < 0 && a[j]>0) {
temp = a[j];
a[j] = a[i];
a[i] = temp;
i++;
j--;
}
else if (a[i] < 0 && a[j] < 0) {
i++;
}
}
}
int main()
{
int a[] = {
1,2,3,-5,-1 }; //{-1,2,3,-5,0,1}
Rearrange(a, 5);
for (int i = 0; i <= 4; i++) {
printf("%d\n", a[i]);
}
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门提示:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件