Array K Element Ascending in Python

In this class, we write the code for Array K Element Ascending in Python.

For Complete YouTube Video: Click Here

Array K Element Ascending

The examples we discuss will improve your coding skill. You can easily crack the placement exams.

Take our placement training course that covers all the subjects and practice tests.

Our suggestion, Take the question try to solve it on your own. Then check for a solution.

Q) Given an Array of size N. The array consists of N elements. Input K is taken from the user. K<N and K>0.

Arrange the First K elements in the array in ascending order and N-k elements in descending order.

Example:

Given N=8

Array elements are [8,5,11,2,6,1,13,9]

K=5.

Output: [2,5,6,8,11,13,9,1]

The first k elements are arranged in ascending order. And remaining elements are arranged in descending order.

Program

n = int(input("enter number of elements"))
k = int(input("enter k value. it should be less then n"))
list1=[]
print("enter elements")
for i in range(n):
    x=int(input())
    list1.append(x)
i=0
j=k
while(i < k-1 or j < n-1):
    minimum=list1[i]
    index1=i
    maximum=list1[j]
    index2=j
    if(i < k-1):
        for m in range(i+1,k):
            if list1[m] < minimum:
                minimum=list1[m]
                index1=m
        temp=list1[index1]
        list1[index1]=list1[i]
        list1[i]=temp
        i+=1
    if(j < n-1):
        for m in range(j+1,n):
            if list1[m] > maximum:
                maximum=list1[m]
                index2=m
        temp=list1[index2]
        list1[index2]=list1[j]
        list1[j]=temp
        j+=1
print(list1)

Logic

To sort the elements in ascending or descending order. We can use bubble sort or selection sort.

In the program, we are using selection sort logic. Click here.

By using small changes in the condition of selection sort, we can arrange elements in descending order.

We have to apply selection sort ascending logic on the first k elements. Descending logic on remaining elements.

We divided the array into two parts. First K elements one part and Other elements second part.

Logic to loop on the elements of two lists already discussed. Click here.

We can quickly write the code using selection sort logic and the logic used to loop on two lists.

Whatever logic we discussed in the entire course will help you write the code for many other problems.

The while loop in the above program is used to loop in the two partitions.

One partition from index position zero to index position k-1.

Other partition from index position k to index position n-1.

Inside the loop, apply selection sort ascending logic to the first partition.

Selection sort descending logic to other partition.

Based on the assumption reader is good at selection sort logic.

Leaving the remaining code to the reader to analyze. For better practice.