5.Move negative elements to one side of the array.
5.Move negative elements to one side of the array.
Problem link :- click here
Problem method :- Partition(quick sort, quick select)
C code
//move negative elements
#include<stdio.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void move_neg(int A[], int start, int end)
{
int i, j, pivot;
pivot = 0;
i = start-1;
j = start;
for(j=start; j<end; j++)
{
if(A[j] < pivot)
{
i++;
swap(&A[i], &A[j]);
}
}
i++;
swap(&A[i], &A[end]);
}
void main()
{
int arr[30];
int n, i;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of the array\n");
for(i=0; i<n; i++)
scanf("%d",&arr[i]);
printf("Given Array\n");
for(i=0; i<n; i++)
printf("\t%d",arr[i]);
printf("\n");
move_neg(arr, 0, n-1);
printf("\n\nArray after moving the negative elements to one side\n");
for(i=0; i<n; i++)
printf("\t%d",arr[i]);
printf("\n\n");
}
Java code
package programs;
import java.util.*;
public class Array__5
{
static void move_neg(int arr[], int start, int end)
{
int pivot, i, j, temp;
pivot = 0;
i = start-1;
j = start;
for(j=start; j<=end; j++)
{
if(arr[j] < pivot)
{
i++;
if(i!=j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args)
{
int array[] = new int[20];
int n, i;
Scanner s = new Scanner(System.in);
System.out.print("Enter the size of the array :");
n = s.nextInt();
System.out.println("Enter the elements of the array :");
for(i=0; i<n; i++)
array[i] = s.nextInt();
System.out.println("Given Array :");
print_array(array, n);
move_neg(array, 0, n-1);
System.out.println("\n\nArray after moving negative elements to left side :");
print_array(array, n);
}
static void print_array(int arr[], int n)
{
for(int i=0; i<n; i++)
System.out.print(arr[i] + " ");
}
}
Time complexity :- O(n)
Space complexity :- O(1)
In this video see only the partition function.
Comments
Post a Comment