按字母顺序排序与另一个数组同步的数组



我正在编写一个简单的程序,目前,该程序将输入的名称和标记写入两个独立的数组,数组计数器同步。例如,第一个数组的条目#3中的名称与第二个数组的条目的标记相对应。到目前为止,我的代码是这样的:

import java.io.*;
public class project
{
    int ctr;
    int ctr1;
    int pos;
    int temp;
    int max;
    public static void main(String args[]) throws IOException
    {
        new project().input();
    }
    void input() throws IOException
    {
        BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
        System.out.println ("How many children?");
        int n = Integer.parseInt(obj.readLine());
        String a[] = new String[n];
        int b[] = new int[n];
        for(ctr=0;ctr<n;ctr++)
        {
            System.out.println("Enter name");
            a[ctr]=obj.readLine();
            System.out.println("Enter marks");
            b[ctr]=Integer.parseInt(obj.readLine());
        }
    }
}

我现在想按字母顺序对名称列表进行排序,这样当按顺序打印数组时,名称按字母顺序从A到Z排列。

在不使用任何函数(如compareTo()sort())的情况下按字母顺序对字符串数组进行排序,而使用嵌套循环进行冒泡或交换排序的最佳方法是什么

如何同步排序,以便在第一个数组中对名称进行混洗时,相应的标记进行相同的混洗,从而保持数据的正确性

首先,我建议不要这样做。我会创建一个包含名称和标记的类,将其存储在数组中,并对生成的数组进行排序。

然后,如果你真的想这样做,例如在冒泡排序中,当普通代码说要交换你正在排序的数组中的元素i和j时,只需交换另一个数组中的元件i和j。这将完成任务。

代码是用c++编写的,但您可以将其转换为java,并根据需要进行更改。当我试图为基于优先级的CPU调度的非抢占版本编写代码时,我也遇到了类似的问题。尝试同步两个的排序

#include <bits/stdc++.h>
using namespace std;
  
// Function to sort character array b[]
// according to the order defined by a[]
void pairsort(int a[], char b[], int n)
{
    pair<int, char> pairt[n];
  
    // Storing the respective array
    // elements in pairs.
    for (int i = 0; i < n; i++) 
    {
        pairt[i].first = a[i];
        pairt[i].second = b[i];
    }
  
    // Sorting the pair array.
    sort(pairt, pairt + n);
      
    // Modifying original arrays
    for (int i = 0; i < n; i++) 
    {
        a[i] = pairt[i].first;
        b[i] = pairt[i].second;
    }
}
  
// Driver function
int main()
{
    int a[] = {2, 1, 5, 4, 9, 3, 6, 7, 10, 8};
    char b[] = {'A', 'B', 'C', 'D', 'E', 'F', 
                         'G', 'H', 'I', 'J'};
                           
    int n = sizeof(a) / sizeof(a[0]);
      
    // Function calling
    pairsort(a, b, n);
  
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
    cout << endl;
  
    for (int i = 0; i < n; i++)
        cout << b[i] << " ";
          
    return 0;
}

相关内容

最新更新