/*
#面试编程题#将数组里的负数排在数组的前面,
正数排在数组的后面。但不改变原先负数和正数的排列顺序。
例:input: -5,2,-3, 4,-8,-9, 1, 3,-10;
output: -5, -3, -8, -9, -10, 2, 4, 1, 3。*/
自己想到的有两个思路,
第一个思路是直接对数组进行修改,首先要确定数组的尾部一定全是正数,需要将尾部的负数前移到刚好后面出现正数的地方,然后index定位到此处,往前找第一个正数,按题目要求的规则移到后面地方,index减一,按此方法将数组调整
第二个思路简单,建立两个辅助数组a、b,正的放a,负的放入b ,最后输出b、a里的元素即可
贴上代码:
ps:代码中的index可能有些乱,以后写的时候会注意,抱歉
1 #include<iostream>
2 using namespace std;
3 void adjust1(int *a,int len)
4 {
5 int i,j,k;
6 int temp;
7 if(a[len-1] < 0)
8 {
9 i = len -1;
10 temp = a[i];//baocun zuihouyige fushu
11 j = i-1;
12 while(a[j] > 0)
13 {
14 a[j+1] = a[j];
15 j--;
16 }
17 j ++;
18 a[j] = temp;//make the last part all positive numbers
19 }
20 else if (a[len-1] < 0)
21 {
22 j = len-1;
23 while(a[j] > 0)
24 {
25 j--;
26 }
27 }
28 while(j > 0)
29 {
30 k = j;
31 while(a[j] < 0)
32 {
33 j--;
34 }
35 if(a[j] > 0 && j > 0)
36 {
37 while(j<k)
38 {
39 temp = a[j];
40 a[j] = a[j+1];
41 a[j+1] = temp;
42 j++;
43 }
44 }
45 j = k-1;
46 }
47 for(i = 0;i<len;i++)
48 {
49 cout << a[i] << " ";
50 }
51 cout << endl;
52 }
53 void adjust2(int *a,int len)
54 {
55 int b[len];
56 int c[len];
57 int i,j,k;
58 for(i = 0;i<len;i++)
59 {
60 b[i]=0;
61 c[i]=0;
62 }
63 j = 0;
64 k = 0;
65 for(i = 0;i<len;i++)
66 {
67 if(a[i] > 0)b[j++] = a[i];
68 else c[k++] = a[i];
69 }
70 i = 0;
71 while(c[i]!=0)
72 {
73 cout << c[i++] << " ";
74 }
75 i = 0;
76 while(b[i]!=0)
77 {
78 cout << b[i++] <<" ";
79 }
80 }
81 int main()
82 {
83 int a[] = {-5,2,-3,4,-8,-9,1,3,-10};
84 int i;
85 for(i = 0;i<sizeof(a)/sizeof(int);i++)
86 {
87 cout << a[i] << " ";
88 }
89 cout << endl;
90
91 adjust1(a,9);
92 adjust2(a,9);
93 system("pause");
94
95 return 0;
96
97 }
3 void adjust1(int *a,int len)
4 {
5 int i,j,k;
6 int temp;
7 if(a[len-1] < 0)
8 {
9 i = len -1;
10 temp = a[i];//baocun zuihouyige fushu
11 j = i-1;
12 while(a[j] > 0)
13 {
14 a[j+1] = a[j];
15 j--;
16 }
17 j ++;
18 a[j] = temp;//make the last part all positive numbers
19 }
20 else if (a[len-1] < 0)
21 {
22 j = len-1;
23 while(a[j] > 0)
24 {
25 j--;
26 }
27 }
28 while(j > 0)
29 {
30 k = j;
31 while(a[j] < 0)
32 {
33 j--;
34 }
35 if(a[j] > 0 && j > 0)
36 {
37 while(j<k)
38 {
39 temp = a[j];
40 a[j] = a[j+1];
41 a[j+1] = temp;
42 j++;
43 }
44 }
45 j = k-1;
46 }
47 for(i = 0;i<len;i++)
48 {
49 cout << a[i] << " ";
50 }
51 cout << endl;
52 }
53 void adjust2(int *a,int len)
54 {
55 int b[len];
56 int c[len];
57 int i,j,k;
58 for(i = 0;i<len;i++)
59 {
60 b[i]=0;
61 c[i]=0;
62 }
63 j = 0;
64 k = 0;
65 for(i = 0;i<len;i++)
66 {
67 if(a[i] > 0)b[j++] = a[i];
68 else c[k++] = a[i];
69 }
70 i = 0;
71 while(c[i]!=0)
72 {
73 cout << c[i++] << " ";
74 }
75 i = 0;
76 while(b[i]!=0)
77 {
78 cout << b[i++] <<" ";
79 }
80 }
81 int main()
82 {
83 int a[] = {-5,2,-3,4,-8,-9,1,3,-10};
84 int i;
85 for(i = 0;i<sizeof(a)/sizeof(int);i++)
86 {
87 cout << a[i] << " ";
88 }
89 cout << endl;
90
91 adjust1(a,9);
92 adjust2(a,9);
93 system("pause");
94
95 return 0;
96
97 }