Reputation: 73
Suppose I have an array with following elements
int arr2[]={21,31,41,51,54,29,15,18,19,16,17};
and I have second array arr
int arr[]={4,2,5};
Now I want to sort arr2 with the help of arr in ACS in such a way that it gets sorted like this and final array becomes
Final array should be 21,31,41,51,29,54,15,16,17,18,19
note that arr[0]=4 hence first four elements are sorted in ASC 21,31,41,51
then arr[1]=2 hence next two elements are sorted in ACS, so it becomes 21,31,41,51,29,54
then arr[2]=5 hence next five elements will be sorted in ASC, so it becomes 21,31,41,51,29,54,15,16,17,18,19
now final array becomes 21,31,41,51,29,54,15,16,17,18,19
how can I do this kind of sorting ?
Code I am using to do this is
int arr2[]={21,31,41,51,54,29,15,18,19,16,17};
int arr[]={4,2,5};
I am able to achieve the result with below code but the problem is I can't make it short when the number of array/elements are not known.
for (i=0;i<4-1;i++)
{
for (j=i+1;j<4; j++)
{
if( arr[i] > arr[j] )
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (i=5;i<6-1;i++)
{
for (j=i+1;j<7; j++)
{
if( arr[i] > arr[j] )
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (i=7;i<11-1;i++)
{
for (j=i+1;j<10; j++)
{
if( arr[i] > arr[j] )
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
Upvotes: 1
Views: 69
Reputation: 3486
http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-byte:A-int-int-
There is Arrays.sort
method which accepts ranges. Solution to your problem becomes:
int arr2[]={21,31,41,51,54,29,15,18,19,16,17};
int arr[]={4,2,5};
int start_index = 0;
for(int i=0; i < arr.length; ++i)
{
Arrays.sort(arr2,start_index,start_index+arr[i]);
start_index += arr[i];
}
Upvotes: 1