第一个算法的python代码如下,测试通过
def suanfa1(num,list1):
length = len(list1)
p1 = -1
for i in range(length):
if list1[i] < num:
list1[p1 + 1],list1[i] = list1[i],list1[p1 + 1]
p1 += 1
模型就是不断通过p1指针去交换大于num的数字和小于num的数字,p1是指向小数区最右边的数字,每次交换就++。
c代码如下:
include <stdio.h>
void suanfa1(int number, int (*p)[ ]);
void suanfa1(int number, int (*p)[ ]){
int temp;
int *p1 = p - 1;
while(p++){
if (number > *p){
temp = *(p+1);
*(p+1) = *(p1);
*p1 = temp;
p1 ++ ;
}
}
}
int main(){
int baseNumber = 2;
int (*p)[ ] = testArray;
int testArray[10] = {7,1,-1,3,7,8,-4,5}
suanfa1(baseNumber,testArray);
while(p++){
printf("%d",*p);
}
return 0;
}
荷兰国旗代码如下,通过测试:
p1是指向low区里的最右边的数字,p2是缓冲区的目前数字的指针,p3是最后一个缓存区的数字的位置
def helan(num,list1):
i = len(list1)
p1 = -1
p2 = 0
p3 = i - 1
while not p2 == p3:
if list1[p2] == num:
p2 += 1
elif list1[p2] < num:
list1[p2] ,list1[p1 + 1] = list1[p1 + 1], list1[p2]
p1 += 1
p2 += 1
else:
list1[p2] ,list1[p3] = list1[p3], list1[p2]
p3 -= 1