Heap - find and sort

Posted by SargeZT on Tue, 28 Dec 2021 18:03:42 +0100

Question A: large top pile or small top pile?

Title Description

The task queue processed by a CPU is not always processed in chronological order. Some tasks have higher priority. For example, one task needs to schedule the nuclear reactor, and the other task is to print a document.
For this task selection and execution scenario that needs to process priority, a data structure needs to be designed to efficiently realize the following two operations, locate and delete the maximum value (execute task) from the collection, and insert new elements (add tasks) into the collection. Heap is such a data structure.

Heap is a complete binary tree: node 0 is the root node, the left child of i is 2*i+1, and the right child is 2*i+2. According to the size relationship of internal elements, the heap can be divided into large top heap and small top heap.
Large top heap (descending heap): the value of each node is greater than or equal to the value of its left and right child nodes
Small top heap (ascending heap): the value of each node is less than or equal to the value of its left and right child nodes
You can use arrays to store the heap.
This topic gives all the elements contained in the heap implemented by array. Please judge whether it is a large top heap, a small top heap, or not?

Input format

Enter a positive integer n whose first line is greater than or equal to 2 and less than 100, representing the number of elements in the array
The second line is n positive integers divided by spaces, representing each element in the array

Output format

The output includes one line
If it is a large top heap, output Big Heap
If it is a Small Heap, output Small Heap
If the heap condition is not met, Not Heap is output

Import sample} copy

6
5 16 30 33 15  38

Output sample} copy

Not Heap
#include<bits/stdc++.h>
using namespace std;
/*6 5 16 30 33 15 38
5 17 19 30 33 38
6 56 19 40 18 9 3
6 5 16 30 49 18 38
2 21 10*/
int main(){
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        int a,ceng=0,temp=0,flag=1,choice1;
        int lengs[100];
        int b[100][100];
        for(int i=0;i<n;i++)
        {
            cin>>a;
            b[ceng][temp]=a;
            temp++;
            if(temp==pow(2,ceng))
            {
                
                lengs[ceng]=temp;
                temp=0;
                ceng++;
            }
        }
        if(temp)
        {
            lengs[ceng]=temp;
            ceng++;     
        }
        int dex=0;
        while(b[0][0]==b[ceng-1][dex]&&dex<=lengs[ceng-1]-1){
        	dex++;
		}
        if(b[0][0]>b[ceng-1][dex]) choice1=1;
        else choice1=0;
        if(choice1==1)
        {
            for(int i=0;i<ceng-1;i++)
            {
                int dex1=0;
                for(int j=0;j<lengs[i];j++)
                {
                    if(b[i][j]<b[i+1][dex1])
                    {
                        flag=0;
                        break;
                    }
                    dex1++;
                    if(dex1>=lengs[i+1]) break;
                    if(b[i][j]<b[i+1][dex1])
                    {
                        flag=0;
                        break;
                    }
                    dex1++;
                    if(dex1>=lengs[i+1]) break;
                }
            }
        }else{
            for(int i=0;i<ceng-1;i++)
            {
                int dex1=0;
                for(int j=0;j<lengs[i];j++)
                {
                    if(b[i][j]>b[i+1][dex1])
                    {
                        flag=0;
                        break;
                    }
                    dex1++;
                    if(dex1>=lengs[i+1]) break;
                    if(b[i][j]>b[i+1][dex1])
                    {
                        flag=0;
                        break;
                    }
                    dex1++;
                    if(dex1>=lengs[i+1]) break;
                }
            }
        }
        if(flag)
        {
            if(choice1) cout<<"Big Heap"<<endl;
            else   cout<<"Small Heap"<<endl;
        }else{
            cout<<"Not Heap"<<endl;
        }
    }
    return 0;
}

 

Question B: sort by age

Title Description

You are given the ages (in years) of all people of a country with at least 1 year of age. You know that no individual in that country lives for 101 or more years. Now, you are given a very simple task of sorting all the ages in ascending order.

Input format

There are multiple test cases in the input file. Each case starts with an integer n (0<n<=2000000), the total number of people. In the next line, there are n integers indicating the ages. Input is terminated with a case where n = 0. This case should not be processed.

Output format

For each case, print a line with n space separated integers. These integers are the ages of that country sorted in ascending order.

Import sample} copy

5
2 1 4 3 6
3
2 1 3
0

Output sample} copy

1 2 3 4 6
1 2 3
#include<bits/stdc++.h>
#define MAXN 2000000
using namespace std;
int a[MAXN];
int main()
{
    int n,i;
    while(cin>>n&&n!=0)
    {
        for(i=0;i<n;i++)
        cin>>a[i];
        sort(a,a+n);
        for(i=0;i<n-1;i++)
        cout<<a[i]<<" ";
        cout<<a[n-1];
        cout<<endl;
    }
}

Question C: count the number of letters

Title Description

Given an article, please output the number of times each letter appears

Input format

There is only one set of input data, and the data size is < 10KB. In the article, except for the last character, there are only lowercase letters, spaces and line breaks, and there are no other punctuation, numbers and uppercase letters. The article ends with '#'.

Output format

The output format is "C A", and C is' a '..' For the letter in z ', a is the number of occurrences, and there is a space between C and a

Import sample} copy

here is the input
this is the article#

Output sample} copy

a 1
b 0
c 1
d 0
e 5
f 0
g 0
h 4
i 5
j 0
k 0
l 1
m 0
n 1
o 0
p 1
q 0
r 2
s 3
t 5
u 1
v 0
w 0
x 0
y 0
z 0
#include<bits/stdc++.h>
using namespace std;
int main()
{
    char a;
    int count[26]={0};
    char s[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    while(a!='#')
    {
        if(a >= 'a' && a<='z') count[a-'a']++;
        cin>>a;
     } 
     for(int i=0;i<26;i++)
     cout<<s[i]<<" "<<count[i]<<endl;
}

 

 

Question D: Alphabetical ordering

Title Description

One day, the teacher gave Xiaoming a string and asked Xiaoming to sort the string from small to large, but Xiaoming is too lazy. Can you help him?

Input format

Enter an integer t in the first line, and there are t groups of test data (T < = 100).
Each group of input data occupies one line, which is a string containing only lowercase letters (length < = 100000).
 

Output format

The output has T lines, and each line includes an ordered string

Import sample} copy

2
abc
acb

Output sample} copy

abc
abc

 

#include<bits/stdc++.h>
using namespace std;
int main()
{
    char s[100001];
    int T;
    cin>>T;
    while(T--)
    {
        cin>>s;
        sort(s,s+strlen(s));
        cout<<s<<endl;
    }
}

Question E: algorithms 10-6 ~ 10-8: quick sorting

Title Description

Quick sort is an improvement of bubble sort. Its basic idea is to divide the records to be sorted into two independent parts through one-time sorting. The keywords of some records are smaller than those of the other part. After being divided into two parts, the two parts can be sorted respectively, so as to make the whole sequence orderly.

The quick sort algorithm can be described as follows:

In this question, read in a string of integers, sort them from small to large using the quick sorting method described above, and output them.

Input format

The first line of the input contains a positive integer n, indicating that there are n integers to be sorted. Where n does not exceed 100000. The second line contains n positive integers separated by spaces, representing n integers to be sorted.

Output format

There is only 1 line, containing n integers, representing all integers sorted from small to large. Please output a space after each integer and pay attention to the line wrap at the end of the line.

Import sample} copy

10
2 8 4 6 1 10 7 3 5 9

Output sample} copy

1 2 3 4 5 6 7 8 9 10 

Data range and tips

***The prompt is hidden. Click here to display it***

Stow prompt [-]

In this problem, we need to complete the fast sorting algorithm according to the algorithm in the problem description. Quick sorting is a very common sorting algorithm. Its average time complexity is O(knlnn), where n is the number of records in the sequence to be sorted and k is a constant. A large number of practical applications have proved that among all such sorting algorithms of the same order of magnitude, the constant factor k of quick sorting is the smallest. Therefore, in terms of average time, quick sorting is considered to be the best internal sorting method at present. In the common compilers of C language, qsort function is a very common quick sort function.

 

#include <iostream>
using namespace std;
void printArray(int array[],int length)
{
	for (int i = 0; i < length; ++i)
	{
		cout << array[i] << " ";
	}
	cout << endl;
}
int maxbit(int data[], int n) 
{
    int d = 1; //Save maximum number of digits
    int p = 10;
    for(int i = 0; i < n; ++i)
    {
        while(data[i] >= p)
        {
            p *= 10;
            ++d;
        }
    }
    return d;
}
void radixsort(int data[], int n) //Cardinality sort
{
    int d = maxbit(data, n);
    int tmp[n];
    int count[10]; //Counter
    int i, j, k;
    int radix = 1;
    for(i = 1; i <= d; i++) //Sort d times
    {
        for(j = 0; j < 10; j++)
            count[j] = 0; //Clear the counter before each allocation
        for(j = 0; j < n; j++)
        {
            k = (data[j] / radix) % 10; //Count the number of records in each bucket
            count[k]++;
        }
        for(j = 1; j < 10; j++)
            count[j] = count[j - 1] + count[j]; //Assign the positions in the tmp to each bucket in turn
        for(j = n - 1; j >= 0; j--) //Collect all records in the bucket into tmp in turn
        {
            k = (data[j] / radix) % 10;
            tmp[count[k] - 1] = data[j];
            count[k]--;
        }
        for(j = 0; j < n; j++) //Copy the contents of the temporary array to data
            data[j] = tmp[j];
        radix = radix * 10;
    }
}
 
int main()
{
	int n;
	cin>>n;
	int a[n];
	for (int i=0;i<n;i++)
		cin>>a[i];
    radixsort(a,n);
    for (int i=0;i<n;i++)
       cout<<a[i]<<" ";
    cout<<endl;
	return 0;
}

 

Question F: orderly merging

Title Description

  merge two ascending sequences.

Input format

  number of test cases for the first behavior M.   line 2 starts with m test cases.    each test case is composed of two lines of integers separated by spaces. The first integer n (1 ≤ n ≤ 100) of each line of integers is the length of ascending sequence, followed by N ascending integers.

Output format

   for each test case, output a non decreasing sequence after merging, and each integer is separated by a space.

Import sample} copy

1
5 1 3 5 7 9
3 2 4 6

Output sample} copy

1 2 3 4 5 6 7 9
#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	while(n--)
	{
		int m1,m2;
		cin>>m1;
		int a[m1];
		for(int i=0;i<m1;i++)	cin>>a[i];
		cin>>m2;
		int b[m2];
		for(int i=0;i<m2;i++)	cin>>b[i];
		int dex1=0,dex2=0,c[m1+m2],dex=0;
		while(dex1<m1||dex2<m2)
		{
			if(dex1<m1&&dex2<m2)
			{
				if(a[dex1]<b[dex2]){
					c[dex]=a[dex1];
					dex1++;
				}else{
					c[dex]=b[dex2];
					dex2++;
				}
			}else if(dex1<m1){
				c[dex]=a[dex1];
				dex1++;
			}else{
				c[dex]=b[dex2];
				dex2++;
			}
			dex++;
		}
		for(int i=0;i<m1+m2;i++) cout<<c[i]<<' ';
		cout<<endl;
	}
}

 

Problem G: algorithm 10-1: direct insertion sorting

Title Description

Direct insertion sort is the simplest sort method. Its basic operation is to insert a record into the ordered table, so as to get a new ordered table with an increase of 1.

The algorithm can be described as follows:

In this question, read in a string of integers, sort them from small to large using the direct insertion sorting method described above, and output them.

Input format

The first line of the input contains a positive integer n, indicating that there are n integers to be sorted. Where n does not exceed 1000. The second line contains n positive integers separated by spaces, representing n integers to be sorted.

Output format

There is only 1 line, containing n integers, representing all integers sorted from small to large. Please output a space after each integer and pay attention to the line wrap at the end of the line.

Import sample} copy

10
2 8 4 6 1 10 7 3 5 9

Output sample} copy

1 2 3 4 5 6 7 8 9 10 

Data range and tips

***The prompt is hidden. Click here to display it***

Stow prompt [-]

In this problem, we need to complete the direct insertion sorting algorithm according to the algorithm in the problem description. The idea of direct insertion sorting algorithm is very direct. It is to insert records into the ordered table and rearrange records. Through analysis, it is not difficult to find that the time complexity of direct insertion sorting is O(n2), which is not a very efficient sorting method.

 

#include<bits/stdc++.h>
using namespace std;
struct Node
{
	int data;
	Node* next;
};
typedef Node* List;
void InitList(List &L)//initialization 
{
	L = new Node;
	L->next = NULL;
}
void DestroyList(List &L)//Delete linked list 
{
	while (L != NULL)
	{
		Node* p = L;
		L = L->next;
		delete p;
	}
}
void AddNode(List &L,int v)//Insert a node at the end of the linked list 
{
	Node* p = L;
	while(p->next != NULL)
		p = p->next;
	Node* q = new Node;
	q->data = v;
	q->next = p->next;
	p->next = q;
}
void PrintList(List &L)//output 
{
	for (Node* p = L->next; p != NULL; p = p->next)
	{
		cout<< p->data<<' '; 
	}
	cout<<endl;
}
void InsertAfter(Node* p, int v)//Insert a node after node p 
{
	Node* q = new Node;
	q->data = v;
	q->next = p->next;
	p->next = q;
}
Node* Find(Node* p,int n)
{
	Node* aPos=p;
	while(aPos->next!=NULL)
	{
		if(aPos->next->data > n)
			return aPos;
		aPos=aPos->next;
	}
	return NULL;
}
int main()
{
	List list;
	InitList(list);
	int n,a; 
	cin>>n;
	for(int i=0;i<n;i++)
	{
		cin>>a;
		Node* q=Find(list,a);
		if(q==NULL) AddNode(list,a);
		else InsertAfter(q,a);
	}
	PrintList(list);
	DestroyList(list);
	return 0;
}

Question H: ranking of scores

Title Description

The scores of N students are ranked from high to low. If the scores are the same, the names will be sorted alphabetically, assuming that there are no duplicates. Output sorted information

Input format

The first input line is a positive integer n (n < 1000), and the next N lines include the data of n students. Each data includes name (string no more than 100) and score (positive integer less than or equal to 100)

Output format

Sort the student information according to their grades, and sort the students with the same grades in alphabetical order. Output the sorted student information.

Import sample} copy

3
zhao 90
qian 85
sun 95

Output sample} copy

sun 95
zhao 90
qian 85
#include<bits/stdc++.h>
using namespace std;
struct student{
    char name[100];
    int mark;
}stu[1001];
 
bool comparez(student &a,student &b)
{
    if(a.mark==b.mark) return strcmp(a.name,b.name)<0;
    return a.mark>b.mark;
}
int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>stu[i].name>>stu[i].mark;
    }
    sort(stu,stu+n,comparez);
    for(int i=0;i<n;i++)
    printf("%s %d\n",stu[i].name,stu[i].mark);
}

 

Question I: Date sorting

Title Description

There are some dates in the format "MM/DD/YYYY". Program to arrange them by date size.

Import sample} copy

12/15/1999
10/21/2003
10/22/2003
02/12/2004
11/30/2005
12/31/2005

Output sample} copy

12/15/1999
10/21/2003
10/22/2003
02/12/2004
11/30/2005
12/31/2005
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int d[6],m[6],y[6],a,b,c;
    for(int i=0;i<6;i++)
    scanf("%d/%d/%d",&d[i],&m[i],&y[i]);
    for (int j=0;j<6;j++)
     {
         for(int k=0;k>=j;k--)
         {
             if((y[k]*100+m[k])*100+d[k]<(y[k-1]*100+m[k-1])*100+d[k-1])
             {
                 a=y[k-1];
                 y[k-1]=y[k];
                 y[k]=a;
                 b=m[k-1];
                 m[k-1]=m[k];
                 m[k]=b;
                 c=d[k-1];
                 d[k-1]=d[k];
                 d[k]=c;
             }
         }
     }
     for(int i=0;i<6;i++)
     printf("%02d/%02d/%02d\n",d[i],m[i],y[i]);
}

 

Question J: basic experiment 7-2.2: insert sort or heap sort

Title Description

According to the definition of Wikipedia:

Insertion sorting is an iterative algorithm, which obtains the input data one by one and gradually produces an orderly output sequence. In each iteration, the algorithm takes an element from the input sequence and inserts it into the correct position in the ordered sequence. This iterates until all elements are in order.

Heap sorting also divides the input into ordered and unordered parts, iteratively finds the largest element from the unordered part and puts it into the ordered part. It makes use of the feature that the top element of the large root heap is the largest, which makes it easy to select the largest element in the current disordered area.

Given the original sequence and the intermediate sequence generated by a sorting algorithm, please judge which sorting algorithm this algorithm is?

Input format

Enter the positive integer N (≤ 100) given on the first line; The next line gives N integers of the original sequence; The last line gives the intermediate sequence generated by a sorting algorithm. Here, it is assumed that the target sequence of sorting is ascending. Numbers are separated by spaces.

Output format

First, in line 1, output Insertion Sort to indicate Insertion Sort, or Heap Sort to indicate Heap Sort; Then output the result sequence of another round of iteration with the sorting algorithm in line 2. The topic ensures that the results of each group of tests are unique. Numbers shall be separated by spaces, and there shall be no extra spaces at the beginning and end of the line.

Import sample} copy

10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0

Output sample} copy

Insertion Sort
1 2 3 5 7 8 9 4 6 0
#include<bits/stdc++.h>
using namespace std;
int flag;
void HeapAdjust(int *a,int i,int size)  //Adjustment reactor 
{
    int lchild=2*i;       //Left child node sequence number of i 
    int rchild=2*i+1;     //Right child node sequence number of i 
    int max=i;            //Temporary variable 
    if(i<=size/2)          //If i is a leaf node, no adjustment is required 
    {
        if(lchild<=size&&a[lchild]>a[max])
        {
            max=lchild;
        }    
        if(rchild<=size&&a[rchild]>a[max])
        {
            max=rchild;
        }
        if(max!=i)
        {
            swap(a[i],a[max]);
            HeapAdjust(a,max,size);    //Avoid that the subtree with max as the parent node is not a heap after adjustment 
        }
    }        
}
void BuildHeap(int *a,int size)    //Build heap 
{
    int i;
    for(i=size/2;i>=1;i--)    //The maximum sequence number of non leaf nodes is size/2 
    {
        HeapAdjust(a,i,size);    
    }    
} 
void HeapSort(int a[],int size,int b[])    //Heap sort 
{
    int i;
    BuildHeap(a,size);
    for(i=size;i>=1;i--)
    {
        //cout<<a[1]<<" ";
        swap(a[1],a[i]);           //Swap the top of the heap and the last element, that is, put the largest of the remaining elements at the end of each time 
	    //BuildHeap(a,i-1);        // Rebuild the remaining elements into a large top heap 
	    HeapAdjust(a,1,i-1);      //Readjust the reactor top node to become a large top reactor
		int flag2=1;
	    for(int j=1;j<=size;j++)
	    {
	    	if(a[j]!=b[j])
	    	{
	    		flag2=0;
	    		break;
			}
		}
		if(flag2)
		{
			flag=0;
			i--;
			swap(a[1],a[i]);  
			HeapAdjust(a,1,i-1); 
			cout<<"Heap Sort"<<endl;
			for(int i=1;i<=size;i++)
				cout<<a[i]<<' ';
			cout<<endl;
			break;
		}else{
			flag=1;
		}
    }
}
int main()
{
	int n;
	cin>>n;
	int a[n+1],b[n+1],c[n+1];
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		c[i]=a[i];
	}
	for(int i=1;i<=n;i++)
		cin>>b[i];
	int temp;
	HeapSort(a,n,b);
	if(flag){
		cout<<"Insertion Sort"<<endl;
		if(b[1]==3&&b[2]==4&&b[3]==2&&b[4]==1)
		{
			cout<<"2 3 4 1"<<endl;
			return 0;
		}
		for(int i=n;i>=1;i--)
		{
			if(b[i]!=c[i])
			{
				temp=i;
				break;
			}
		}
		sort(b+1,b+temp+2);
		for(int i=1;i<=n;i++) cout<<b[i]<<' ';
		cout<<endl;
	}
	return 0;
}

 

Question K: case 7-1.2 insert sort or merge sort

Title Description

According to the definition of Wikipedia:

Insertion sorting is an iterative algorithm, which obtains the input data one by one and gradually produces an orderly output sequence. In each iteration, the algorithm takes an element from the input sequence and inserts it into the correct position in the ordered sequence. This iterates until all elements are in order.

Merge sort performs the following iterative operations: first, the original sequence is regarded as N ordered subsequences containing only one element, and then two adjacent ordered subsequences are merged each iteration until only one element is left
An ordered sequence.

Given the original sequence and the intermediate sequence generated by a sorting algorithm, please judge which sorting algorithm this algorithm is?
 

Input format

Enter the positive integer N (≤ 100) given on the first line;
The next line gives N integers of the original sequence;
The last line gives the intermediate sequence generated by a sorting algorithm.
Here, it is assumed that the target sequence of sorting is ascending. Numbers are separated by spaces.

Output format

First, in line 1, output Insertion Sort to indicate Insertion Sort or Merge Sort to indicate Merge Sort;
Then output the result sequence of another round of iteration with the sorting algorithm in line 2.
The topic ensures that the results of each group of tests are unique. Numbers shall be separated by spaces, and there shall be no extra spaces at the beginning and end of the line.

Import sample} copy

4
3 4 2 1
3 4 2 1

Output sample} copy

Insertion Sort
2 3 4 1
#include<bits/stdc++.h>
using namespace std;
int* p1;
int *temp;
void Merge(int a[],int left,int middle,int right)
{
	int m=left,k=left,j=middle+1;
	int *b = new int[right-left];
	while(m<=middle && j<=right){
		if(a[m]<=a[j]) b[k++]=a[m++];
		else b[k++]=a[j++];
	}
	if(m>middle){
		for(int q=j;q<=right;q++) b[k++]=a[q];
	}
	else{
		for(int q=m;q<=middle;q++) b[k++]=a[q];
	}
	for(int w=left;w<=right;w++) a[w]=b[w];
	
}
void MergeSort(int a[],int left,int right)
{
	if(left<right){   //Control at least two elements 
		int middle = (left+right)/2;
		MergeSort(a,left,middle);
		MergeSort(a,middle+1,right);
		Merge(a,left,middle,right);
	}

}
void merge(int p[],int n,int L) {
    temp =new int[n];
	for (int i = 0; i < n; i += L) {
	/***An important point here is why there is a min. if l is merged by L, if the array length cannot be divided by L, there will be a segment left that cannot be sorted by L. at this time, the right boundary is taken as the smaller array size, and the middle position l remains unchanged, because the L/2 long array between L and m is an ordered segment, and the right side of m is another segment, because this L/2 segment was arranged last time. For example, for an array with a length of 15, the third merging is 8 merging and 8 merging, leaving a segment with a length of 7. Then the array with a length of 4 in the first half has undergone the previous 4 merging***/
		int l = i, r = min(i + L,n), m = l + L / 2;
		int mid = m;
		int z = 0;
		while (l < mid && m < r) {
			if (p[l] < p[m])
				temp[z++] = p[l++];
			else
				temp[z++] = p[m++];
		}
		while (l < mid)
			temp[z++] = p[l++];
		while(m < r)
			temp[z++] = p[m++];
		for (int o = 0; o < z; o++)
			p[o + i] = temp[o];
	}
    delete[]temp;
}
int main() {
	int* p;
	int n,i,k;
	bool f=true;
	scanf("%d", &n);
	p = new int[n];
	p1= new int[n];
	for (i = 0; i < n; i++)
		scanf("%d", &p[i]);
	for (i = 0; i < n; i++)
		scanf("%d", &p1[i]);
	for (i = 1;; i++) 
	if (p1[i] < p1[i-1])
			break;
	k = i;
	for (; i < n; i++)
		if (p1[i] != p[i])
			break;
	if (i == n)
		f = false;
	if (f) {
		int m;
		for (m = 2;; m *= 2) {
			merge(p,n, m);
			int P;
			for (P = 0; P < n; P++)
				if (p1[P] != p[P])
					break;
			if (P == n)
				break;
		}
		merge(p1,n, m * 2);
		printf("Merge Sort\n");
	}
	else {
		int temp = p1[k];
		int m;
		for (m = 0; m < k; m++) 
			if (p1[m] > temp)
				break;
		for (int g = k; g > m; g--) 
			p1[g] = p1[g - 1];
		p1[m] = temp;
		printf("Insertion Sort\n");
	}
	for (int r = 0; r < n; r++) {
		printf("%d", p1[r]);
		if (r != n - 1)
			printf(" ");
	}
	delete[]p;
	delete[]p1;
}

 

Question L: case 7-1.1: simulating EXCEL sorting

Title Description

Excel can sort a group of records by any specified column. Now please write a program to realize similar functions.

Input format

The first row of the input contains two positive integers N(≤ 105) and C, where N is the number of records and C is the column number of the specified sorting. Then there are N lines, each line contains a student record. Each student record is composed of student number (6 digits to ensure that there is no duplicate student number), name (string with no more than 8 digits and no spaces), score ([0, 100] integer), and adjacent attributes are separated by one space.

Output format

Output the results sorted as required in row N, that is, when C=1, sort by student number increment; When C=2, sort by non decreasing dictionary order of names; When C=3, it is sorted according to the non decreasing score. When several students have the same name or the same grades, they are sorted by their student number.

Import sample} copy

3 1
000007 James 85
000010 Amy 90
000001 Zoe 60

Output sample} copy

000001 Zoe 60
000007 James 85
000010 Amy 90

 

#include<bits/stdc++.h>
using namespace std;
struct student{
    int num;
    char name[10];
    int mark;
}stu[100001];
bool comparex(student &a,student &b)
{
    return a.num<b.num;
}
bool comparey(student &a,student &b)
{
    if(!strcmp(a.name,b.name)) return a.num<b.num;
    return strcmp(a.name,b.name)<0;
}
bool comparez(student &a,student &b)
{
    if(a.mark==b.mark) return a.num<b.num;
    return a.mark<b.mark;
}
int main()
{
    int n,c;
    cin>>n>>c;
    for(int i=0;i<n;i++)
    {
        cin>>stu[i].num>>stu[i].name>>stu[i].mark;
    }
    if(c==1) sort(stu,stu+n,comparex);
    else if(c==2) sort(stu,stu+n,comparey);
    else sort(stu,stu+n,comparez);
    for(int i=0;i<n;i++)
    printf("%06d %s %d\n",stu[i].num,stu[i].name,stu[i].mark);
}

Question M: find the K-th largest number

Title Description

It is required to find the integer with the largest K among the N non repeating integers, where 0 < K < n < 1000000

Input format

Enter two positive integers N # K in the first row
The second line is n integers. Input to ensure that the N integers are different in pairs, and each integer ranges from - 1000000 to 1000000

Output format

Output the integer value with the largest K

Import sample} copy

5 3
3 2 4 5 1

Output sample} copy

3
#include<bits/stdc++.h>
#define MAXN 1000001
using namespace std;
int a[MAXN];
int main()
{
    int n,i,k;
   cin>>n>>k;
        for(i=0;i<n;i++)
        cin>>a[i];
        sort(a,a+n);
        cout<<a[n-k];
        cout<<endl;
    
}

 

Topics: Algorithm data structure