Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Program has 1 function swaps() that puts negative elements in the
- leftmost indices, and positive elements in the rightmost indices.
- It does not necessarily order the elements by size however.
- It uses two pointers that start by pointing to the beginning
- and end of the array. When the two pointers meet, the swapping is done.*/
- #include <stdio.h>
- #include <stdlib.h>
- #define N 8 // some arbitrary array length just for testing
- // Takes an array as parameter, modifies its elements, and returns the modified array
- int* swaps(int* array);
- void main(){
- // Create and initialize an int array
- int i;
- int *array = malloc(sizeof(int)*N);
- // remember to add spacebar between input integers
- for(i = 0; i < N; i++){
- scanf("%d", &array[i]);
- }
- // Print before swapping
- for(i = 0; i < N; i++){
- printf("[");
- printf("%d", array[i]);
- if(i == N-1){
- printf("] ");
- } else {
- printf("],");
- }
- }
- printf("\n");
- // Call swaps with argument being the newly created array of length N
- swaps(array);
- // Print after swapping
- for(i = 0; i < N; i++){
- printf("[");
- printf("%d", array[i]);
- if(i == N-1){
- printf("] ");
- } else {
- printf("],");
- }
- }
- printf("\n");
- }
- // Time complexity is O(n^2), however this problem should be able to solve in O(n)
- int* swaps(int* array){
- int* ptr1;
- ptr1 = &array[0];
- int* ptr2;
- ptr2 = &array[N-1];
- int tmp;
- for(ptr1; ptr1 <= &array[N-1]; ptr1++){
- if(ptr1==ptr2){
- return array;
- }
- if(*ptr1 >= 0){
- for(ptr2; ptr2 >= &array[0]; ptr2--){
- if(ptr1==ptr2){
- return array; // have to check ptr2==ptr1 all the time, otherwise ptr2 will keep iterating
- }
- // swap elements that ptr1 and ptr2 point to
- if(*ptr2 < 0){
- tmp = *ptr2;
- *ptr2 = *ptr1;
- *ptr1 = tmp;
- ptr2--;
- if(ptr1==ptr2){
- return array; // have to check ptr2==ptr1 after ptr 2 decr, otherwise ptr2 will keep iterating
- }
- break;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement