When chatting in the group last night, a friend asked Baidu how to answer his pen questions. At that time, no one seemed to be able to answer the questions as required. I thought about it today after work, but I do not know whether or not, you can run it with vc6 and the execution is correct. I would like to give you more comments.
The question is as follows:
Assume that an integer array contains positive numbers and negative numbers. Now, an algorithm is used to make all negative numbers of the array to the left of the positive number,
The relative positions of negative and positive elements remain unchanged. Time-Space complexity requirements: O (N), O (1)
For example
-3 4 2-1 7 3-5
After sorting
-3-1-5 4 2 7 3
Before answering the questions, I first tested how to use memset,
Function Name: memset
Function: Set all bytes in S to CH, and the size of S array is given by N
Usage: void * memset (void * s, char CH, unsigned N );
Program example:
# Include <string. h>
# Include <stdio. h>
# Include <mem. h>
Int main (void)
{
Char buffer [] = "Hello world \ n ";
Printf ("buffer before memset: % s \ n", buffer );
Memset (buffer, '*', strlen (buffer)-1 );
Printf ("buffer after memset: % s \ n", buffer );
Return 0;
}
What if the source character to be copied overlaps with the target string? Will the copy fail? I tested it. It's okay.
char str[30] = "0123456789";
memcpy(&str[0],&str[5],10);
printf("%s\n",str);
// memcpy(&str[5],&str[0],10);----->012340123456789
// memcpy(&str[0],&str[5],10);----->56789
Below I will post the code to answer that question. I hope you will give me more advice.
// Testbaidu. cpp: defines the entry point for the console application.
//
/*
Assume that an integer array contains positive numbers and negative numbers. Now, an algorithm is used to make all negative numbers of the array to the left of the positive number,
The relative positions of negative and positive elements remain unchanged. Time-Space complexity requirements: O (N), O (1)
For example
-3 4 2-1 7 3-5
After sorting
-3-1-5 4 2 7 3
*/
# Include "stdafx. H"
// # Include <stdio. h>
# Include <string. h>
Void print_arr (int * P, int N)
{
For (INT I = 0; I <n; I ++)
{
Printf ("% 3d", P [I]);
}
Printf ("\ n ");
}
Int main (INT argc, char * argv [])
{
/*
Char STR [30] = "0123456789 ";
Memcpy (& STR [0], & STR [5], 10 );
Printf ("% s \ n", STR );
// Memcpy (& STR [5], & STR [0], 10); ----- & gt; 012340123456789
// Memcpy (& STR [0], & STR [5], 10); ----- & gt; 56789
*/
Int A [] = {-3, 4, 2,-1, 7, 3,-5 };
Int Len = sizeof (a)/sizeof (INT );
Printf ("% 3d:", 0 );
Print_arr (A, Len );
Int COUNT = 0;
Int temp;
For (INT I = 0; I <Len; I ++)
{
If (A [I] <0)
{
If (count> 0)
{
Temp = A [I];
Memcpy (& A [I-count + 1], & A [I-count], count * sizeof (INT ));
A [I-count] = temp;
}
}
Else if (a [I]> 0)
{
Count ++;
}
Printf ("% 3d:", I );
Print_arr (A, Len );
}
Printf ("% 3d:", 0 );
Print_arr (A, Len );
Printf ("Hello world! \ N ");
Return 0;
}