0

I have a struct of employee data and it 2 separated fields of first name and last name. i want to sort this array by first name and in case of 2 names are the same then sort them by last name. I already sorted the array by the first name but still cant do it by the last name in case 2 first names are the same. I want to implement this sort without using any built-in functions in .Net such as array.sort() i just want to use loops.

public struct EmployeeData
        {
            public char sex;
            public int age;
            public int id1;
            public int id2;
            public int id3;
            public string fname;
            public string lname;
            public int seniority;
        }
    static EmployeeData[] SortByFirstName(EmployeeData[] empdata)
        {
            int min = 0;
            EmployeeData temp;
            for (int i = 0; i < empdata.Length; i++)
            {
                for (int j = i+1; j < empdata.Length; j++)
                {
                    if (empdata[i].fname.Length < empdata[j].fname.Length)
                    {
                        min = empdata[i].fname.Length;
                    }
                    else
                    {
                        min = empdata[j].fname.Length;
                    }

                    for (int k = 0; k < min; k++)
                    {
                        if (empdata[i].fname[k] > empdata[j].fname[k])
                        {
                            temp = empdata[i];
                            empdata[i] = empdata[j];
                            empdata[j] = temp;
                            break;
                        }
                        else if (empdata[i].fname[k] == empdata[j].fname[k])
                        {
                            continue;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            return empdata;

        }
1
  • did my solution work for you? Commented Aug 3, 2016 at 12:25

1 Answer 1

1

Change your sort function to handle both first name and last name.

Where you say

else if (empdata[i].fname[k] == empdata[j].fname[k])
    {
         continue;
    }

Instead of continuing, sort the two entries by last name..

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.