Emma wishes to give her father a bouquet for
his birthday. She asks for help from her
mother Rosy. Rosy gives N flower sticks
numbered 1 to N to Emma and tells her to
arrange them in the bouquet in a particular
order. She asks Emma to arrange the first K
flower sticks in the order of increasing length
and the remaining sticks in the order of
decreasing length.
Write an algorithm to find the final
arrangement of the flower sticks in the
bouquet.
Answers
Algorithm:
Step 1: Start
Step 2: Take input from the user in the variables N and K.
Step 3: Create an array len[] of N elements
Step 4: Take input in the array from the user
Step 5: Sort the array using bubble sort technique
- Step 1: Repeat step 1 to 4 for(i = 0 ; i < N ; i++)
- Step 2: For(j = 0 ; j < N - i - 1 ; j++)
- Step 3: if(len[j] > len[j+1])
- Step 4: swap(len[j] , len[j+1])
- Step 5: End
Step 6: Print first K elements
- Step 1: Repeat step 1 and 2 for (i = 0 ; i < K ; i++)
- Step 2: Print len[i]
- Step 3: End
Step 6: Print remaining elements
- Step 1: Repeat step 1 and 2 for (i = N - 1 ; i >= K ; i--)
- Step 2: Print len[i]
- Step 3: End
Step 7: End
Program in C++:
#include<iostream>
using namespace std;
int main()
{
int N, K;
cout<<"Enter total number of sticks : ";
cin>>N;
cout<<"Enter number given by Rosy : ";
cin>>K;
int len[N];
cout<<"Enter the lengths of the sticks : ";
for(int i = 0 ; i < N ; i++)
{
cin>>len[i];
}
for(int i = 0 ; i < N ; i++)
{
for(int j = 0 ; j < N - i - 1 ; j++)
{
if(len[j] > len[j+1])
{
int temp = len[j];
len[j] = len[j+1];
len[j+1] = temp;
}
}
}
cout<<"Final arrangement : ";
for(int i = 0 ; i < K ; i++)
{
cout<<len[i]<<"\t";
}
for(int i = N-1 ; i >= K ; i--)
{
cout<<len[i]<<"\t";
}
return 0;
}
Output:
Enter total number of sticks : 8
Enter number given by Rosy : 4
Enter the lengths of the sticks : 2 4 6 8 1 3 5 7
Final arrangement : 1 2 3 4 8 7 6 5