Alternate sorting: Given an array of integers, rearrange the array in such a way that the first element is first maximum and second element is first minimum.
Eg.) Input : {1, 2, 3, 4, 5, 6, 7}
Output : {7, 1, 6, 2, 5, 3, 4}
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n,t,j;
scanf("%d",&n);
int *a=(int *)malloc(n*sizeof(int)); // creating dynamic array
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
//sorting
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
t=n-1;j=0;
//printing alternate min max
for(i=0;i<n;i++)
{
if(i%2!=0){
printf("%d ",a[j] ); ++j;}
else{
printf("%d ",a[t] ); --t;}
}
return 0;
}
OUTPUT :
Excellent blog.Really useful one
ReplyDeletePgms woriking very use full
ReplyDeleteit is useful
ReplyDeleteinput:6
ReplyDelete8 5 6 1 3 4
output:
3 1 6 4 8 5
#include
#include
void fn_sorting(int *arr, int n)
{
int temp, i, j;
for(i=0; i arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(i=1; i arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(i=0; i<n; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int num, i, j, *ptr;
scanf("%d", &num); // enter the number of elements
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
for(i = 0; i < num; i++)
{
scanf("%d", ptr + i);
}
fn_sorting(ptr, num);
return 0;
}
#include
Delete#include
void fn_sorting(int *arr, int n)
{
int temp, i, j;
for(i=0; i arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(i=1; i arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(i=0; i<n; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int num, i, j, *ptr;
scanf("%d", &num); // enter the number of elements
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
for(i = 0; i < num; i++)
{
scanf("%d", ptr + i);
}
fn_sorting(ptr, num);
return 0;
}
python
ReplyDeleteinput:6
8 5 6 1 3 4
output:
3 1 6 4 8 5
a=int(input())
l=list(map(int,input().split()))
for i in range(0,a,2):
for j in range(i+2,a,2):
if(l[i]>l[j]):
l[j],l[i]=l[i],l[j]
for i in range(1,a,2):
for j in range(i+2,a,2):
if(l[i]>l[j]):
l[j],l[i]=l[i],l[j]
print(*l,sep=" ")